Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Optional Comparison Operators
Written by Team Kodeco

In Swift, you can compare two optionals for equality without unwrapping the optionals first. When you do this, the comparison is made between the wrapped values if both optionals are non-nil, or the comparison returns false if either optional is nil.

For example, the following code compares two optional integers for equality:

var firstNum: Int? = 5
var secondNum: Int? = 5

if firstNum == secondNum {
  print("The numbers are equal")
} else {
  print("The numbers are not equal")
}
// Output: The numbers are equal

firstNum = nil
if firstNum == secondNum {
  print("The numbers are equal")
} else {
  print("The numbers are not equal")
}
// Output: The numbers are not equal

In contrast, when using other comparison operators like < or >, you must unwrap the optionals first:

let firstNum: Int? = 5
let secondNum: Int? = 7

if firstNum! < secondNum! {
    print("firstNum is less than secondNum")
} else {
    print("firstNum is greater than secondNum")
}
// Output: firstNum is less than secondNum
© 2024 Kodeco Inc.