- 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.
- 程序設(shè)計(jì)與實(shí)踐(VB.NET)
- 信息可視化的藝術(shù):信息可視化在英國
- Visual C++串口通信技術(shù)詳解(第2版)
- Flash CS6中文版應(yīng)用教程(第三版)
- Mastering Swift 2
- Java程序設(shè)計(jì)入門
- HoloLens與混合現(xiàn)實(shí)開發(fā)
- 區(qū)塊鏈架構(gòu)之美:從比特幣、以太坊、超級(jí)賬本看區(qū)塊鏈架構(gòu)設(shè)計(jì)
- Mastering SciPy
- INSTANT JQuery Flot Visual Data Analysis
- Applied Deep Learning with Python
- 流暢的Python
- 威脅建模:設(shè)計(jì)和交付更安全的軟件
- Web前端開發(fā)全程實(shí)戰(zhàn):HTML5+CSS3+JavaScript+jQuery+Bootstrap
- Go語言從入門到進(jìn)階實(shí)戰(zhàn)(視頻教學(xué)版)