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

后端 未结 4 1777
野趣味
野趣味 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:20

    When you are using ! and the variable is nil it will trigger run time error but if use ? it will fail gracefully. More detail information in apple document

    0 讨论(0)
  • 2020-12-28 16:23

    Both symbols ! and ? used for optionals. 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.Otherwise It will crash if variable value is nil.And if you are using ?, Application will not crash in nil case.

    You can follow this link for more information:- https://www.youtube.com/watch?v=twBfiKsbHP8

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-28 16:32

    Use attachment.image!.size if you're guaranteed that image? isn't nil. If you're wrong (and it is nil) your app will crash. This is called forced unwrapping.

    If you're not sure it won't be nil, use image?.

    In your case image! is OK, since you control whether placeholder.png exists.

    Read all of the documentation on Swift Optionals. It's a basic and fundamental part of the language.

    0 讨论(0)
提交回复
热议问题