Viewcontroller Is Declared but Its Value Is Never Read
Last calendar week, I wrote almost weak and strong outlets. But there's another question well-nigh outlets that comes upwards often. Should outlets be alleged as optionals or implicitly unwrapped optionals? This tutorial zooms in on the pros and cons of each of these options.
What Does Apple tree Recommend
Final week, nosotros first explored what Apple tree recommends by creating a project in Xcode and that's a proficient place to start. Launch Xcode and create a new projection. Choose the Single View Application template and name the project Outlets.
Open Principal.storyboard, bring upwardly the Object Library on the right, and add a label to the View Controller Scene.
Press Option and click ViewController.swift in the Projection Navigator to open the Assistant Editor. Create an outlet past pressing Control and dragging from the UILabel
instance in the View Controller Scene to ViewController.swift in the Assistant Editor on the right.
Proper name the outlet label
and click Create to take Xcode create the outlet.
If you've read terminal week'southward tutorial, then information technology shouldn't surprise you lot that the outlet is declared strong, not weak. What'southward of special interest to us is the blazon of the outlet, UILabel!
. The outlet is alleged equally an implicitly unwrapped optional, non an optional. Recall that the @IBOutlet
Interface Architect attribute indicates the holding is an outlet.
@IBOutlet var label: UILabel!
What Is the Difference Between Optionals and Implicitly Unwrapped Optionals
Before we go on our word most outlets, information technology'due south important to empathise what the difference is between optionals and implicitly unwrapped optionals. The departure is obvious thanks to Swift's expressive syntax. Nether the hood, an implicitly unwrapped optional is an optional. Only the exclamation marking in the property declaration unmistakably indicates that we're taking a risk. Whenever you come across an assertion mark, you demand to be on guard.
You probably know that an optional has a value or information technology doesn't. Manifestly and simple. The reason many developers are not fond of optionals is considering yous cannot straight access the value of an optional. To safely admission the value of an optional, you need to unwrap information technology. Optional binding is a construct that lets you safely access the optional'south value.
var message: String? = "Hello, World" if let message = bulletin { impress(message) }
If you're absolutely certain an optional contains a value, you lot tin have a shortcut by force unwrapping the value stored in the optional. To force unwrap an optional, we append an exclamation mark to the name of the variable or constant. Congratulations. You've saved yourself an if
statement and two lines of code. Merely is this worth the chance? That's the question you always need to inquire yourself when using the exclamation marking in Swift.
var message: Cord? = "Hello, World" print(message!)
The exclamation mark warns united states that we're taking a chance. We're nearly to perform an functioning that can backlash. If bulletin
doesn't have a value, a fatal fault is thrown and the application terminates immediately. That's the risk you're taking.
Convenience Over Rubber
Implicitly Unwrapped Optionals Are Convenient
Why would you desire to use an implicitly unwrapped optional? The answer is very elementary. Clarity and convenience. Most developers use implicitly unwrapped optionals considering it's convenient. But information technology's worth mentioning that implicitly unwrapped optionals tin also bring clarity to your code by eliminating the need for optional bounden and optional chaining.
The value of the characterization
outlet we declared before in the ViewController
class can be accessed similar any other variable. That's just possible because we declared characterization
as an implicitly unwrapped optional.
Be warned, though, if y'all forget to connect the label
outlet in Interface Builder and you access the label
property in the ViewController
course, your application crashes due to a fatal error the awarding cannot recover from. That'southward the take chances you're taking. But there's more.
Optionals Are Safe
If you don't like risks, then declaring an outlet as optional is the safest option. Menstruation. The downside is that you need to piece of work with an optional. To access the value stored in the optional, you demand to safely unwrap it. If y'all want to accept a shortcut by force unwrapping the optional, then you might equally well have declared the outlet every bit an implicitly unwrapped optional in the first place.
Why Are Outlets Declared as Optionals
Have you ever wondered why outlets are alleged as optionals or implicitly unwrapped optionals? The reason is simple. Earlier an instance of a course or construction finishes initialization, every stored property needs to have a valid value.
Classes and structures must set up all of their stored properties to an appropriate initial value past the time an example of that grade or structure is created. Stored backdrop cannot be left in an indeterminate land. — The Swift Programming Language
If you don't know what value a stored belongings should have during initialization, and then you tin can assign a default value or you can declare the property equally an (implicitly unwrapped) optional. And that brings the states to the reason why outlets are declared as (implicitly unwrapped) optionals.
The value of an outlet cannot be prepare during initialization. Let's revisit the project we created earlier. When the view controller is instantiated, its view hasn't been loaded yet. It'due south only after the view controller is initialized that information technology loads its view. This likewise means that any outlets declared in the view controller class don't accept a value immediately after the view controller'southward initialization. That's why an outlet is always declared as an (implicitly unwrapped) optional.
What Are the Risks
With the above in mind, you should now understand what the risks are when you declare an outlet equally an implicitly unwrapped optional. If you lot forget to connect an outlet in Interface Builder, so your application crashes when the outlet is accessed. But that isn't the most of import risk. This is easy to fix in development and should never happen in production. If you've properly tested your application, your application won't suffer from this type of trouble.
The most important risks accept to do with accessing an outlet earlier its value is set up. If you access an outlet before or while the view controller loads its view, you lot can run into a runtime error.
Information technology's important to remember that y'all're taking a risk every time you apply an implicitly unwrapped optional. Considering of the potential risk involved, some developers avoid using implicitly unwrapped optionals for outlets. It'southward the safest choice, but it comes with some overhead.
While I see the benefit of using optionals instead of implicitly unwrapped optionals, I always declare outlets as implicitly unwrapped optionals, the reason being clarity and convenience.
When Non to Utilize an Implicitly Unwrapped Optional
I promise information technology's clear that any property, including outlets, that tin can become cipher
during the lifetime of the object that owns information technology, should never be declared as an implicitly unwrapped optional.
Source: https://cocoacasts.com/should-outlets-be-optionals-or-implicitly-unwrapped-optionals
0 Response to "Viewcontroller Is Declared but Its Value Is Never Read"
Post a Comment