What is difference between “?” and “!” in Swift?

后端 未结 4 1797
野趣味
野趣味 2020-12-28 16:03

I know what \"?\" and \"!\" mean when I declare variables in Swift. But what do they mean when using these variables? For example, in this code:

var         


        
4条回答
  •  轮回少年
    2020-12-28 16:26

    what is ! and ?:

    • Use ? if the value can become nil in the future, so that you test for this.
    • Use ! if it really shouldn't become nil in the future, but it needs to be nil initially.

    if You are using attachment.image!.size any variable with ! means, compiler don't bother about that variable has any value or nil. it goes to take action further, it will here try to get size of image. if attachment.image is nil then app will be crash here.

    While, attachment.image?.size, this will make sure you, if attachment.image isn't nil then further action will be take place, otherwise But it confirm Application will not be crash in case of nil value of image .

    Summary:

    We should have to use !, when we make sure option type variable has value at a time and we need to take action on it further, Otherwise.

提交回复
热议问题