In Swift, what does the ! symbol mean in a function signature?

前端 未结 2 2061
感动是毒
感动是毒 2020-12-01 07:10

In a Swift function signature, what does the ! after an argument imply? More specifically, does it mean the argument needs to be unwrapped before it is passed i

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 08:10

    The exclamation point after type declaration in the Swift method signatures means the parameter is an Implicitly Unwrapped Optional. That means it is an Optional type (that would be normally denoted with ? after the type) that gets unwrapped every time you access it in the method body. Not as it is passed in. It is as if you used forced unwrapping — sender!.titleLabel — each time you use it, but you do not have to type the exclamation point every time — hence implicitly unwrapped optional.

    From Using Swift with Cocoa and Objective-C, section Working with nil:

    Because Objective-C does not make any guarantees that an object is non-nil, Swift makes all classes in argument types and return types optional in imported Objective-C APIs. Before you use an Objective-C object, you should check to ensure that it is not missing.

    Implicitly unwrapped optional allows you to treat it in the Swift code like a normal value type with the caveat that accessing it when it is nil will interrupt your program with runtime error. You’d guard against that using if statements, optional binding or optional chaining.

    Implicitly unwrapped optionals are pragmatic compromise to make the work in hybrid environment that has to interoperate with existing Cocoa frameworks and their conventions more pleasant, while also allowing for stepwise migration into safer programing paradigm — without null pointers — enforced by the Swift compiler. You’ll meet them all over Cocoa APIs, but there are also some use cases for them in pure Swift as discussed in Why create "Implicitly Unwrapped Optionals"?

提交回复
热议问题