Junior — Middle
Is it possible to perform comparison of Optional type objects in code?
sobes.tech AI
Answer from AI
In Swift, objects of type Optional can be compared with each other if the type they wrap supports comparison. For example, if you have Optional<Int>, you can use the == and != operators for comparison.
Comparison works as follows:
- If both values are
nil, they are considered equal. - If one is
niland the other is not, they are not equal. - If both are not
nil, their internal values are compared.
Example:
let a: Int? = 5
let b: Int? = 5
let c: Int? = nil
print(a == b) // true
print(a == c) // false
print(c == nil) // true
If the type does not support comparison, then Optional of that type cannot be compared directly.