为什么当等式运算符可以时,Swift的大于或小于运算符不能比较选项
发布时间:2020-12-14 04:38:29 所属栏目:百科 来源:网络整理
导读:在 Swift 3中,这是一个编译错误,如果我使用或者 let a: Int?guard a 0 else {return}guard a 0 else {return} 编译错误: Value of optional type ‘Int?’ not unwrapped; did you mean to use ‘!’ or ‘?’? 但是,如果我与==或!=进行比较,那也没关系 le
在
Swift 3中,这是一个编译错误,如果我使用>或者<
let a: Int? guard a > 0 else {return} guard a < 0 else {return} 编译错误:
但是,如果我与==或!=进行比较,那也没关系 let a: Int? guard a == 0 else {return} guard a != 0 else {return} 解决方法
对于等式运算符来说,支持选项非常有意义,因为对于任何整数值变量i来说绝对清楚:
> nil == nil 另一方面,目前尚不清楚如何与nil进行比较: 我不到零吗? >如果我想对一个数组进行排序,以便所有的nils在最后出现,那么我希望我小于零. 由于其中任何一个都同样有效,因此标准库不利于其他标准库是没有意义的.它留给程序员实现对他们的用例有意义的任何比较. 这是一个玩具实现,它生成一个比较运算符以适应这两种情况: func nilComparator<T: Comparable>(nilIsLess: Bool) -> (T?,T?) -> Bool { return { switch ($0,$1) { case (nil,nil): return true case (nil,_?): return nilIsLess case (_?,nil): return !nilIsLess case let (a?,b?): return a < b } } } let input = (0...10).enumerated().map { $0.offset % 2 == 0 ? Optional($0.element) : nil } func concisePrint<T>(_ optionals: [T?]) -> String { return "[" + optionals.map { $0.map{ "($0)?" } ?? "nil" }.joined(separator: ",") + "]" } print("Input:",concisePrint(input)) print("nil is less:",concisePrint(input.sorted(by: nilComparator(nilIsLess: true)))) print("nil is more:",concisePrint(input.sorted(by: nilComparator(nilIsLess: false)))) 输出:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |