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

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.

主站蜘蛛池模板: 平度市| 惠来县| 彭州市| 定襄县| 平度市| 湘乡市| 中宁县| 奉贤区| 遂川县| 工布江达县| 湖口县| 扶绥县| 平南县| 英德市| 富顺县| 柳州市| 深水埗区| 乌海市| 五台县| 乐亭县| 乐都县| 电白县| 天长市| 胶州市| 神池县| 修文县| 岳池县| 诏安县| 枣强县| 衡阳市| 两当县| 平乡县| 施甸县| 塘沽区| 尉氏县| 西昌市| 抚顺县| 平塘县| 怀柔区| 利川市| 武胜县|