官术网_书友最值得收藏!

Optionals and optional bindings

Use optionals when a value cannot be set. Think of optionals as containers that can take either a value or nil. Optionals gives us the ability to check whether the value is nil or not. To create an optional value, you will have to provide it with a data type followed by a question mark (?). Before we do that, let's create a string that is not an optional. Add the following to Playgrounds:

Now, let's add an optional to Playgrounds:

In this example, we created a string optional, and, if you notice in the Results Panel, it is nil. But for our notAnOptional, we see "This is not an optional". Now, on the next line, let's set optional equal to "This is an optional":

In our Results Panel, we see "This is an optional". Now let's print both notAnOptional and optional, as you will see a difference between the two:

Note that our notAnOptional variable looks fine, but optional has an optional ("") wrapped around the String. The ("") means that, in order for us to access the value, we must unwrap the optional. One way we could do this is by force-unwrapping the optional using an (!). Let's update our print statement and change it to the following:

We force-unwrapped our optional, but this method is not recommended. If you force-unwrap an optional and there is no value, your app will crash, so avoid this. We should use what is called optional binding, which is the safe way to access the value using an if...let statement. Remove the (!) from the print statement and instead write the following optional binding:

This if...let statement is saying that if the optional is not nil, set it to value, but, if this optional is nil, ignore it and do nothing. Now, we do not have to worry about anything regarding setting our value and causing our app to crash.

主站蜘蛛池模板: 伽师县| 旬邑县| 万荣县| 伊吾县| 湖南省| 左云县| 乌恰县| 荥阳市| 西乡县| 衢州市| 定日县| 孙吴县| 潞西市| 津南区| 四子王旗| 洱源县| 阿克苏市| 多伦县| 唐海县| 呼和浩特市| 玉环县| 大石桥市| 文登市| 宁蒗| 阜平县| 乌拉特后旗| 双辽市| 同仁县| 呈贡县| 广东省| 上栗县| 定襄县| 合水县| 呼图壁县| 永城市| 平遥县| 木里| 商河县| 咸丰县| 瓦房店市| 巫山县|