var opt1: Int??? = nil
var opt2: Int?? = nil
print(opt1 == opt2) // why is false?
At first I thought it was because of the different types(Int??? and Int??), so I custom a operator <==> and use the same code as the Optional' == source code to implement it:
extension Optional {
public static func <==> (lhs: Wrapped?, rhs: Wrapped?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l <==> r
case (nil, nil): //I think it should match here
return true
default:
return false
}
}
}
print(opt1 <==> opt2) // false
(the source code link: https://github.com/apple/swift/blob/main/stdlib/public/core/Optional.swift)
I saw from the breakpoint that lhs and rhs become the same type.
In other words, this is not caused by the type.
And Optional' ~= operator implementation in the source code:
public static func ~=(lhs: _OptionalNilComparisonType, rhs: Wrapped?) -> Bool {
switch rhs {
case .some:
return false
case .none:
return true
}
}
According to the code above,I think case (nil, nil): in static func <==> should match, so print(opt1 == opt2) and print(opt1 <==> opt2) should be true, but why it's false?
