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

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.

主站蜘蛛池模板: 泰顺县| 顺义区| 象州县| 石景山区| 昂仁县| 阆中市| 灵宝市| 梨树县| 永寿县| 昆山市| 邯郸市| 太保市| 郴州市| 长岭县| 子洲县| 上栗县| 宁河县| 阳信县| 泽州县| 陇川县| 岳阳市| 禄丰县| 深州市| 泰顺县| 罗城| 巩义市| 刚察县| 郎溪县| 揭西县| 通州区| 台湾省| 含山县| 古丈县| 随州市| 呈贡县| 忻城县| 淮滨县| 南漳县| 武冈市| 读书| 承德县|