This is the definition of the ==
operator that looks like it gets used in this case:
public func ==<T : Equatable>(lhs: T?, rhs: T?) -> Bool
You see that both the first argument (lhs
) and the second argument (rhs
) have to be of the same type, T?
. Since the first argument (optionalString
) is String?
, I think the second argument is cast to String?
too, which makes the comparison work.
I think this proves the idea:
func testCasting<T: Equatable>(a: T?, b: T?) {
print(a, b) // Optional("A") Optional("A")
}
var optionalString: String? = "A"
testCasting(optionalString, b: "A")
In the second argument you pass a literal A
that gets wrapped in an optional to make the types check. The code compiles and runs.
Note that this is completely different from unwrapping the first argument implicitly. That wouldn’t be a safe operation and would undermine the whole point of optionals.