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

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.

主站蜘蛛池模板: 临洮县| 拉孜县| 齐齐哈尔市| 平昌县| 陕西省| 江西省| 德阳市| 化州市| 林西县| 怀集县| 循化| 应用必备| 大方县| 昌黎县| 明溪县| 明光市| 游戏| 湖北省| 攀枝花市| 天峻县| 剑河县| 竹山县| 太仆寺旗| 法库县| 平罗县| 岳池县| 交城县| 县级市| 永定县| 东乡| 饶阳县| 兴国县| 中西区| 郓城县| 南郑县| 清苑县| 南汇区| 浪卡子县| 太康县| 木里| 晋城|