|
The way Optional described makes me think that aren't all data optionals ? In the end , who can always been 100% sure the specific piece of data we are trying to access is there ? Right ? Then, do we need to always mark data with Thank you in advance, Boat |
|
When you create an optional value by using Int?, Date?, String?,... you're saying the data may or may not be there. When you create a value by saying Int, Date, String,... you're saying it has to contain something. So by creating a non-optional value you're saying it absolutely has to have something in there or your program is not going to compile. You create it as non-optional and you assign it something, so you're 100% sure it's there. Optionals are when the data might not be there, i.e. trying to get data from a server, a file, or some other stored data may result in no data coming back, or performing a method on an empty array that hasn't been filled yet, or any instance where the data simply may not exist.
Another example:
|
|
Vince has the right answer! Here are additional examples. ExampleGet a box and write "Boat's Height" on it. Make a declaration that only Once you initialize the box with a value and you declared the box as a If you try to take the value out and put nothing in the box (ie give the box a nil value, your desk will complain again.)
Ask yourself, what's a good value for Optional ExampleNow make a declaration that the box is To use the value, you first must determine if you HAVE A VALUE IN THE BOX. If the box has a value, then you can use it.
What if you don't know a person's height?
|
|
HI Vince, you said:
can I understand it that: By creating an non-optional value , I tell Swift that "Don't compile if there is not value , because it is supposed to have a value for sure" By creating an optional value, I tell Swift that "You may still compile if there is no value, because I am telling you so. " Is my understanding above correct ? Boat |
|
Almost. If you declare a non-optional value the compiler don't let you compile your program if there is no value before accessing it the first time. On the other hand, if you declare an optional value the compiler makes sure you unwrap the value before accessing it (either with So in both cases the compiler helps you to avoid a fatal error at runtime. |
|
SAVE 50% To celebrate Black Friday, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
Sponsor Hacking with Swift and reach the world's largest Swift community!
This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.
All interactions here are governed by our code of conduct.
Link copied to your pasteboard.