Swift3.0 更新后出现比较运算符方法
在将项目更新到swift3.0之后,在一些controller头部会出现 比较运算符的方法
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
在swift3.0中移除了这四种运算符。也就是移除了Optional比较运算符
public func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool
public func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool
public func <= <T : Comparable>(lhs: T?, rhs: T?) -> Bool
public func >= <T : Comparable>(lhs: T?, rhs: T?) -> Bool
Swift的进化给出了如下动机说明
let a: Int? = 4 let b: Int = 5 a < b // b is coerced from "Int" to "Int?" to match the parameter type.
根据上面的代码,如果没有去掉可选类型的比较,b会被强转换为 "Int?"
由此,参照下边的代码可以更好地理解,去掉这个方法的必要,如果没有去掉强转,一些比较就会出现意想不到的结果。
struct Pet {
let age: Int
}
struct Person {
let name: String
let pet: Pet?
}
let peeps = [
Person(name: "Fred", pet: Pet(age: 5)),
Person(name: "Jill", pet: .None), // no pet here
Person(name: "Burt", pet: Pet(age: 10)),
]
let ps = peeps.filter { $0.pet?.age < 6 }
ps == [Fred, Jill] // if you don’t own a pet, your non-existent pet is considered to be younger than any actual pet 🐶
如果你没有宠物,你不应该是查询的结果中的一个,所以Jill不应该在里边。
所以,另一方面,如果强转被移除,为了解决比较的问题,必须对可选值和不可选值的混合体进行明确的处理,这样确保不会出现意外数据。具体代码提现如下
let a: Int? = 4
let b: Int = 5
a < b // no longer works
a < .some(b) // works
a < Optional(b) // works
https://github.com/apple/swift-evolution/blob/master/proposals/0121-remove-optional-comparison-operators.md

浙公网安备 33010602011771号