gpt4 book ai didi

swift - 为什么 Swift 的大于或小于运算符不能比较可选项,而等于运算符可以?

转载 作者:搜寻专家 更新时间:2023-10-31 08:24:51 24 4
gpt4 key购买 nike

在 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
  • nil != i
  • i != nil
  • i == i 当且仅当它们的值相同

另一方面,尚不清楚与 nil 的比较应该如何操作:

i是否小于nil

  • 如果我想对数组进行排序,以便所有 nil 都出现在最后,那么我希望 i 小于 nil
  • 但是如果我想对一个数组进行排序,以便所有 nil 都出现在开头,那么我希望 i 大于 nil

由于其中任何一个都同样有效,因此标准库偏向于其中一个是没有意义的。留给程序员实现对他们的用例有意义的比较。

这是一个玩具实现,它生成一个比较运算符以适应任何一种情况:

func nilComparator<T: Comparable>(nilIsLess: Bool) -> (T?, T?) -> Bool {
return {
switch ($0, $1) {
case (nil, nil): return false
case (nil, _?): return nilIsLess
case (_?, nil): return !nilIsLess
case let (a?, b?): return a < b
}
}
}

let input = (0...10).enumerated().map {
$0.offset.isMultiple(of: 2) ? 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?, nil, 4?, nil, 6?, nil, 8?, nil, 10?]

nil is less: [nil, nil, nil, nil, nil, 0?, 2?, 4?, 6?, 8?, 10?]

nil is more: [0?, 2?, 4?, 6?, 8?, 10?, nil, nil, nil, nil, nil]

关于swift - 为什么 Swift 的大于或小于运算符不能比较可选项,而等于运算符可以?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44808391/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com