- iOS 12 Programming for Beginners
- Craig Clayton
- 324字
- 2021-07-02 15:04:55
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.
- 廣電5G從入門到精通
- Application Development with Qt Creator(Second Edition)
- CorelDRAW X6 中文版圖形設計實戰從入門到精通
- Twilio Cookbook
- Proxmox High Availability
- 物聯網長距離無線通信技術應用與開發
- Unity Artificial Intelligence Programming
- Getting Started with nopCommerce
- Learning Node.js Development
- AWS Lambda Quick Start Guide
- 計算機網絡技術
- Microservices Development Cookbook
- 網絡空間作戰:機理與籌劃
- 互聯網視覺設計(全彩慕課版)
- 從實踐中學習Kali Linux網絡掃描