Why is the ! in Swift called an 'implicitly' rather than 'explicitly' unwrapped optional?

前端 未结 2 990
北海茫月
北海茫月 2021-02-12 18:59

The name of the ! always confuses me: it\'s called an \'implicitly unwrapped optional\'. However, what is implicit about it? Implicit means \"implied though not pla

相关标签:
2条回答
  • 2021-02-12 19:42

    In Swift, trailing exclamation marks (!) are used in two different ways. One is called Forced Unwrapping. This is when you have a variable defined as an Optional and you want to basically assert that the value is not nil so that you can use it as if it were not an optional:

    var optionalName: String? = "World"
    if optionalName != nil {
        sayHelloTo(optionalString!)
    }
    

    An alternate way you could describe "Forced Unwrapping" is "Explicit Unwrapping", but forced adds the extra hint that the whole program will crash if you try to "Force Unwrap" an optional that is nil.

    The second is when you are actually declaring the type of a variable and it is called an Implicitly Unwrapped Optional. This is for when you want to declare a variable that is technically optional, but that you will treat as if it is not optional. Every time you use this Implicitly Unwrapped Optional, it is in reality, doing the "Force Unwrapping" I described above:

    var name: String! = "World"
    if name != nil {
        sayHelloTo(name)
    }
    

    You can still test an Implicitly Unwrapped Optional for nil, but you can also use it directly as if it were not optional. That is why it is considered implicit. Every time you use it, it is automatically, implicitly unwrapped for you.

    Like "Forced Unwrapping" an "Implicitly Unwrapped Optional" will still crash the entire program if you try to use it when it is nil

    0 讨论(0)
  • 2021-02-12 19:46

    Normal Optional

    var foo : Foo? = Foo()
    foo!.doSomething() // explicitly unwrap it and call the method
    

    Implicitly Unwrapped Optional

    var foo : Foo! = Foo()
    foo.doSomething() // implicitly unwrap it and call the method just like it is not optional
    

    In both case, you need something to declare an optional (? or !). Implicitly Unwrapped Optional does not add more. But you can omit unwrap operator when use it.

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