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

Chapter 4. To Be or Not To Be – Optionals

As we discussed in Chapter 2, Building Blocks – Variables, Collections, and Flow Control, all variables and constants must always have a value before they are used. This is a great safety feature because it prevents you from creating a scenario where you forget to give a variable an initial value. It may make sense for some number variables, such as the number of sandwiches ordered to start at zero, but it doesn't make sense for all variables. For example, the number of bowling pins standing should start at 10, not zero. In Swift, the compiler forces you to decide what the variable should start at, instead of providing a default value that could be incorrect.

However, there are other scenarios where you will have to represent the complete absence of a value. A great example is if you have a dictionary of word definitions and you try to lookup a word that isn't in the dictionary. Normally, this will return a String, so you could potentially return an empty String, but what if you also need to represent the idea that a word exists without a definition? Also, for another programmer who is using your dictionary, it will not be immediately obvious what will happen when they look up a word that doesn't exist. To satisfy this need to represent the absence of a value, Swift has a special type called an optional.

In this chapter, we will cover the following topics:

  • Defining an optional
  • Unwrapping an optional
  • Optional chaining
  • Implicitly unwrapped optionals
  • Debugging optionals
  • The underlying implementation
主站蜘蛛池模板: 安吉县| 丹巴县| 辽中县| 陆川县| 平南县| 湘阴县| 宿迁市| 聂拉木县| 雅安市| 马鞍山市| 南郑县| 汶上县| 洪湖市| 基隆市| 太和县| 凤庆县| 景宁| 陇西县| 锡林浩特市| 离岛区| 大名县| 牙克石市| 万源市| 林周县| 志丹县| 留坝县| 南岸区| 阿巴嘎旗| 阜新市| 太原市| 镇沅| 收藏| 屏东县| 温泉县| 永年县| 卢龙县| 宁南县| 光山县| 滁州市| 读书| 台山市|