Optional has the == operator defined for it in the Swift standard library:
func ==<T : Equatable>(lhs: T?, rhs: T?) -> Bool
This means that if the option contains an equivalent value, you can compare two additional parameters. If both parameters are equal to zero, and if two optional values ββare equal, then they are equal.
So, if you donβt care if person.name nil or not, it just contains the value βJohnβ, you can simply write if person.name == "John" .
How does it work when "John" is a String not a String? ? * Since Swift will implicitly convert any type to an optional wrapper, enter if this is what the argument requires. So how does the == function require a String? argument to compare options String? , "John" will be implicitly converted to {Some "John"} , which allows you to use the == operator between two options.
* well, actually, "John" is not a String , its string literal, which is converted to String
source share