The ? identifier means that the variable is optional, meaning its value can be nil. If you have a value in your code, declaring it as non-optional allows the compiler to check at build time if it has a chance to become nil.
You can check whether it is nil in an if statement:
var optionalName: String? = "John Appleseed"
if optionalName {
// <-- here we know it's not nil, for sure!
}
Many methods that require a parameter to be non-nil will declare that they explicitly need a non-optional value. If you have an optional value, you can convert it into non-optional (for example, UIWindow?
-> UIWindow
) by unwrapping it. One of the primary methods for unwrapping is an if let
statement:
var greeting = "Hello!"
// at this point in the code, optionalName could be nil
if let name = optionalName {
// here, we've unwrapped it into name, which is not optional and can't be nil
greeting = "Hello, \(name)"
}
See The Swift Programming Language, page 11 for a brief introduction, or page 46 for a more detailed description.