Thursday, January 18, 2018

What is the question mark ? in Swift?

The question mark ? is used during the declaration of a property, as it tells the compiler that this property is optional. The property may hold a value or not, in the latter case it's possible to avoid runtime errors when accessing that property by using ?. This is useful in optional chaining (see below) and a variant of this example is in conditional clauses.


var optionalName : String? = “John"
if optionalName != nil {
    print(“Your name is \(optionalName!)”)
}