What does an exclamation mark mean in the Swift language?

后端 未结 22 2190
南方客
南方客 2020-11-22 03:47

The Swift Programming Language guide has the following example:

class Person {
    let name: String
    init(name: String) { self.name = name }
    var apar         


        
22条回答
  •  臣服心动
    2020-11-22 04:12

    Here is what I think is the difference:

    var john: Person?
    

    Means john can be nil

    john?.apartment = number73
    

    The compiler will interpret this line as:

    if john != nil {
        john.apartment = number73
    }
    

    While

    john!.apartment = number73
    

    The compiler will interpret this line as simply:

    john.apartment = number73
    

    Hence, using ! will unwrap the if statement, and make it run faster, but if john is nil, then a runtime error will happen.

    So wrap here doesn't mean it is memory wrapped, but it means it is code wrapped, in this case it is wrapped with an if statement, and because Apple pay close attention to performance in runtime, they want to give you a way to make your app run with the best possible performance.

    Update:

    Getting back to this answer after 4 years, as I got the highest reputations from it in Stackoverflow :) I misunderstood a little the meaning of unwrapping at that time. Now after 4 years I believe the meaning of unwrapping here is to expand the code from its original compact form. Also it means removing the vagueness around that object, as we are not sure by definition if it is nil or not. Just like the answer of Ashley above, think about it as a present which could contain nothing in it. But I still think that the unwrapping is code unwrapping and not memory based unwrapping as using enum.

提交回复
热议问题