Swift : Difference in '!' and '?'

2020-03-07 08:58发布

问题:

I declared below:

@IBOutlet var hw_label : UILabel!

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

But when i declare as below :

    @IBOutlet var hw_label : UILabel!

              and 
    hw_label.text = "Hello World"

It display error as Image.

I Just want to know that what is the difference between '!' and '?'.

or why we have to use this..?

回答1:

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



回答2:

? is used for optional values i.e. if you do not know at the time of declaration that variable will have a value or not the declare it as optional. var friendName : String? in this case friendName can be nil

! is used for implicitly unwrapped optional i.e. you are sure that the variable must have value. var employeeId : String! in this case employeeId cannot be nil



回答3:

One more thing:

If you declare a ! mark variable in a class, you have to initialize the values for this variable in the init() method of this class.