在
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 ‘?’?
但是,如果我与==或!=进行比较,那也没关系
let a: Int? guard a == 0 else {return} guard a != 0 else {return}
解决方法
对于等式运算符来说,支持选项非常有意义,因为对于任何整数值变量i来说绝对清楚:
> nil == nil
>没有!=我
>我!=无
> i == i当且仅当它们的值相同时
另一方面,目前尚不清楚如何与nil进行比较:
我不到零吗?
>如果我想对一个数组进行排序,以便所有的nils在最后出现,那么我希望我小于零.
>但是如果我想对一个数组进行排序以便所有的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))))
输出:
Input: [0?,nil,2?,4?,6?,8?,10?]
nil is less: [nil,0?,10?]
nil is more: [0?,10?,nil]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。