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

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.

主站蜘蛛池模板: 平安县| 西平县| 当阳市| 交口县| 额敏县| 阿荣旗| 昭平县| 镶黄旗| 阳新县| 商都县| 梓潼县| 山西省| 安远县| 咸丰县| 若羌县| 阳曲县| 西宁市| 凤城市| 湖州市| 绥中县| 赤城县| 兴隆县| 临澧县| 增城市| 东阳市| 伊金霍洛旗| 昭觉县| 永仁县| 平乡县| 和林格尔县| 屏山县| 宽甸| 青川县| 攀枝花市| 锦州市| 灵宝市| 无棣县| 玉林市| 大同县| 柘城县| 普陀区|