Optionals: If Statements and Forced Unwrapping

If convertedNumber != nil {
    print("convertedNumber contains some integer value.")
}
// Prints "convertedNumber contains some integer value."
If convertedNumber != nil {
    print("convertedNumber has an integer value of \(convertedNumber!).")
}
// Prints "convertedNumber has an integer value of 123."

Additional information

  • You can use an if statement to find out whether an optional contains a value by comparing the optional against nil.
  • If an optional has a value, it’s considered to be “not equal to” nil.
  • Trying to use ! to access a nonexistent optional value triggers a runtime error.

Related concepts

If Statements and Forced Unwrapping

Optionals: If Statements and Forced Unwrapping — Structure map

Clickable & Draggable!

Optionals: If Statements and Forced Unwrapping — Related pages: