加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

为什么当等式运算符可以时,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}

编译错误:

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]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读