swiftsyntaxoption-typeforced-unwrapping

How to understand `!` and `?` in swift?


I'm new in swift.When i declare a variable,or when i get a property of an instance,I find "!" and "?" is everywhere.Doing such things in Objective-C is quite easy,you can even not know the type of class with the "id" type.Why do we need the ! and the ? ?

I want to know the reason of designing ! and ?,instead of how to use them.What's the advantage of having an optional type?


Solution

  • Well...

    ? (Optional) indicates your variable may contain a nil value while ! (unwrapper) indicates your variable must have a memory (or value) when it is used (tried to get a value from it) at runtime.

    The main difference is that optional chaining fails gracefully when the optional is nil, whereas forced unwrapping triggers a runtime error when the optional is nil.

    To reflect the fact that optional chaining can be called on a nil value, the result of an optional chaining call is always an optional value, even if the property, method, or subscript you are querying returns a nonoptional value. You can use this optional return value to check whether the optional chaining call was successful (the returned optional contains a value), or did not succeed due to a nil value in the chain (the returned optional value is nil).

    Specifically, the result of an optional chaining call is of the same type as the expected return value, but wrapped in an optional. A property that normally returns an Int will return an Int? when accessed through optional chaining.

    var defaultNil : Int?  // declared variable with default nil value
    println(defaultNil) >> nil  
    
    var canBeNil : Int? = 4
    println(canBeNil) >> optional(4)
    
    canBeNil = nil
    println(canBeNil) >> nil
    
    println(canBeNil!) >> // Here nil optional variable is being unwrapped using ! mark (symbol), that will show runtime error. Because a nil optional is being tried to get value using unwrapper
    
    var canNotBeNil : Int! = 4
    print(canNotBeNil) >> 4
    
    var cantBeNil : Int = 4
    cantBeNil = nil // can't do this as it's not optional and show a compile time error
    

    Here is basic tutorial in detail, by Apple Developer Committee.