- Swift 4 Programming Cookbook
- Keith Moon
- 214字
- 2021-07-08 10:21:23
How to do it...
We will look at a different scenario where it is appropriate to have an optional variable. Melody and Finn are playing a game. In each round, Finn will hold his hand behind his back and choose a number of fingers to hold up, Melody will guess how many, and Finn will show her how many fingers he had chosen to hold up.
To help keep track of the game, Melody stores how many fingers Finn has held up in a variable. When Finn shows his hand, Melody can enter a value for the number of fingers, but when Finn's hands are behind his back, Melody doesn't know how many fingers Finn is holding up, and so can't store a value for how many fingers are being held up.
Let's enter the following code:
// Start of the game
var numberOfFingersHeldUpByFinn: Int?
// Finn's hand behind his back
numberOfFingersHeldUpByFinn = nil
// Finn shows his hand
numberOfFingersHeldUpByFinn = 3
// Finn puts hand back behind his back
numberOfFingersHeldUpByFinn = nil
// Finn shows his hand
numberOfFingersHeldUpByFinn = 1
print(numberOfFingersHeldUpByFinn)
// End of the game
let lastNumberOfFingersHeldUpByFinn: Int = numberOfFingersHeldUpByFinn!
Unlike the day of the week example, this code compiles without issues, despite the fact that we assign nil to the variable.
- Learn Blockchain Programming with JavaScript
- 嵌入式軟件系統(tǒng)測試:基于形式化方法的自動化測試解決方案
- Building Modern Web Applications Using Angular
- Mastering Kotlin
- PyTorch自然語言處理入門與實戰(zhàn)
- Apache Karaf Cookbook
- Eclipse Plug-in Development:Beginner's Guide(Second Edition)
- 大學計算機基礎(chǔ)(第2版)(微課版)
- Mastering RStudio:Develop,Communicate,and Collaborate with R
- Webpack實戰(zhàn):入門、進階與調(diào)優(yōu)
- 執(zhí)劍而舞:用代碼創(chuàng)作藝術(shù)
- 軟件測試綜合技術(shù)
- Implementing Microsoft Dynamics NAV(Third Edition)
- Java 7 Concurrency Cookbook
- Oracle Database 12c DBA官方手冊(第8版)