About the function called nil in swift

Asked 2 years ago, Updated 2 years ago, 26 views

The description of the part of this image says that if you add "!" when a variable is substituted with nil, it crashes when the instruction is executed.(https://i.stack.imgur.com/PwDZ8.jpg)!
However, in this image on the next page, it says that the variable should be substituted with nil even though the code is marked with !.What do you mean?(https://i.stack.imgur.com/emKQk.jpg)

swift

2022-09-29 21:56

1 Answers

The crash occurs when nil variables are forcibly unwrapped with ! when executed, so if you are sure that a non-nil value is set before ! forces unwrapping with !.

This ViewController is assumed to be instantiated by the Storyboard.When the Storyboard instantiates the ViewController, you specify @IBOutlet and the properties that connect UI components on the Storyboard are automatically instantiated by the Storyboard (for example, UILabel) ViewController properties

In other words, you cannot instantiate the ViewController and substitute the @IBOutlet properties at the same time.You must instantiate the ViewController first.

There is a time lag between instantiating the ViewController and substituting the @IBOutlet property, during which time the label property is set to nil, so this property must be optional.

You can guarantee that the label property will not be nil at runtime because the label property has been replaced by the Storyboard before the ViewController is not a nil issue at runtime.

(Originally, it would be better not to use Optional or !, but since Storyboard and @IBOutlet have existed since before Swift's introduction, this is what Swift's language specifications look like.)


2022-09-29 21:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.