Swift : Difference in '!' and '?' in swift

后端 未结 3 480
情书的邮戳
情书的邮戳 2021-01-07 13:48

I declared below:

@IBOutlet var hw_label : UILabel!

If I write as above than it\'s running successfully,

But when i declare as belo

3条回答
  •  死守一世寂寞
    2021-01-07 14:40

    There are two types of variables in Swift.

    1. Optional Variables
    2. Normal(Non-Optional) Variables

    Optional Variables: The shortest description is Optional variables/objects contains the the property "object-returns-nil-when-non-exist". In objC almost all the object we create is optional variable only. That is the objects has the property "object-returns-nil-when-non-exist" behavior. However, this particular behavior is not needed all the time. So, to identify the optionals the symbols '?' and '!' has been used. Again there are two type of optionals...

    • Normal Optionals(?)
    • Implicitly unwrapped optionals(!)

    Normal optionals:

    var normalOptional : String?
    

    Implicitly unwrapped optionals:

    var specialOptional : String!
    

    Both are having the "optional" behaviour, but the difference is the 'Implicitly unwrapped optional' can also be used as a normal(non-optional) value.

    For instance, the indexPath variable is declared in the function(cellForRowAtIndex) parameter list by default tableview delegate methods. The row value exists when the cellForRowAtIndex is get called. There, the indexPath variable is declared in the function(cellForRowAtIndex) parameter list. So, the unwrapping of 'row' value from 'indexPath' is as follows.

           var rowValue = indexPath?.row // variable rowValue inferred as optional Int value
           or
           var rowValue = indexPath!.row// variable rowValue inferred as normal Int value
    

    Note: When using the '!' unwrapping, have to be very sure that the particular class exists(contains value).

    Hope this link will gives you more idea. What is the intended use of optional variable/constant in swift

提交回复
热议问题