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

前端 未结 2 991
北海茫月
北海茫月 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: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.

提交回复
热议问题