Suppose that you need to write function that takes closure as one of the parameters to call it as a callback. The user of this function should be able to pass nil
instead of closure. Will you use optionals or implicitly unwrapped optionals in this case?
Thanks in advance.
As a complement to Nate's answer (which is imo the solution ), my suggestion is to never use implicitly unwrapped optionals, unless you have a good reason. Deferred initialization is a good reason.
If you are not sure, don't use it
If the optional can be nil during its post-initialization life cycle, don't use it
If you want to avoid typing an extra ?
, don't use it
If a 3rd party function, method or closure passes an optional, don't turn it into an implicitly unwrapped
If a 3rd party function, method or closure provides an implicitly unwrapped... judge by yourself whether to explicitly check for not nil (ie whether to trust that optional will always be not nil)
More generally, if you have doubts about how an implicitly unwrapped works, it's always better to always avoid
Definitely use an optional here, since the expectation is that it could be nil
. When implicitly unwrapped optionals are used, the intention is that they'll never be nil
by the time they're used - the typical example is @IBOutlet
properties that can't be created in the initializer but will be created via the storyboard before they're used in viewDidLoad
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.