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

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.

主站蜘蛛池模板: 大渡口区| 延庆县| 辛集市| 富宁县| 湘潭市| 新建县| 龙海市| 平陆县| 靖远县| 象州县| 开原市| 瓮安县| 凤台县| 安岳县| 拜泉县| 苏州市| 广南县| 吕梁市| 郁南县| 长沙市| 河间市| 北海市| 万荣县| 芜湖县| 刚察县| 湾仔区| 德州市| 绥中县| 肇源县| 井冈山市| 桐柏县| 独山县| 罗田县| 百色市| 新兴县| 余姚市| 伊金霍洛旗| 环江| 皮山县| 镇安县| 黎平县|