Search code examples
classtypesuilabelswift5xcode11

why do we need to foreUnwrap the dataType while creating an object? Swift 5


whenever I go to internet or check projects on online while creating any object in ViewController class I see an exclamation mark(!) at end of data type why is that? for example:@IBOutlet weak var Label:UILabel! so why is that '!' mark or why are we force unwrapping it? And also when I remove it , it gives an error , we can also write like this @IBOutlet weak var Label=UILabel() so why don't we use this?


Solution

  • You need to understand the things step by step to get an answer.

    1. @IBOutlet: This is a property wrapper that tells Xcode to connect an element on the storyboard with the one in .swift file.
    2. The ! mark: This force-unwrap thing is recommended because when the .swift file needs the instance, it's sure to find the connected element in storyboard. We can also write @IBOutlet weak var Label: UILabel? In this case the instance Label would be optional.
    3. @IBOutlet weak var Label=UILabel(): In this case the instance Label's value is overridden with UILabel() immediately after initialization. The @IBOutlet weak var Label! and Label after Label = UILabel() are not the same instances.

    @IBOutlet weak var label: UILabel is equivalent of writing var label: UILabel. Therefore the i-val does not have an initial value and Swift does not allow that. In Swift either you have to assign a value to a variable or make it optional/unwrapped to explicitly deal with nil values. And also when you unwrap the instance with @IBOutlet, you can use it with ? later on like label?.text = "Some text".

    So, we are forced to use ! or ? for an outlet to explicitly make the variable optional as in for other variable declarations. And we don't use = UILabel() after declaration because it overrides the instance created from the Storyboard (initialized with an NSCoder/Coder from the nib).