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

Initialization and mutability

Dictionaries are value types, and they follow the same mutability and initialization as other value types.

Let's use some important dates—the release dates for Swift—to work with dictionaries:

let swiftReleases = [
"2014-09-09": "Swift 1.0",
"2014-10-22": "Swift 1.1",
"2015-04-08": "Swift 1.2",
"2015-09-21": "Swift 2.0",
"2016-09-13": "Swift 3.0",
"2017-09-19": "Swift 4.0",
"2018-03-29": "Swift 4.1",
"2018-09-17": "Swift 4.2"
] // Swift release dates, source Wikipedia

As you can see, the dictionary type is quite simple; it's Dictionary<String, String>, which we can also denote as [String: String].

Similar to the Array and other value types, using the let keyword makes the dictionary immutable, which means the following:

  • You cannot replace the contents of swiftReleases with a new dictionary
  • You cannot add another key/value pair
  • You cannot remove an existing key/value pair
  • You cannot replace an existing key/value pair
  • You cannot use any function or method that have an effect from above

While having the release date as a string is practical for writing the code, it becomes quite impractical if we want to do any kind of date comparison or computation.

In the next sections, we'll explore what we can do with dictionaries.

主站蜘蛛池模板: 荆门市| 昌吉市| 宁陕县| 收藏| 自贡市| 浮山县| 怀集县| 苏尼特右旗| 阿坝| 安溪县| 义乌市| 重庆市| 萨迦县| 新营市| 本溪| 浑源县| 宜兴市| 依兰县| 唐海县| 赞皇县| 宜兰市| 永川市| 濮阳市| 吉林省| 安西县| 登封市| 柏乡县| 连州市| 南和县| 武强县| 宁德市| 平顶山市| 柏乡县| 高尔夫| 乌苏市| 淮北市| 滕州市| 阳新县| 绍兴市| 全州县| 咸丰县|