三、集合类型 Collection Types

  集合类型 Collection Types

  swift提供了数组(Array)和字典(Dictionary)两种集合类型。数组用来存储相同类型的有序的值(Values);字典用来存储相同类型的无序的值(Values),这些值有一个唯一的键(Key)标识它们。

1. 数组 Array

  Swift中的数组可以存储任何类型,包括对象类型和基本数据类型(比如 String, Int, Double, 和 Bool)。数组中的数据类型必须是一致的。

定义方式:

  Array<SomeType>  //或者  

  [SomeType]

var shoppingList: [String] = ["Eggs", "Milk"]

2. 字典 Dictionary

定义方式:

  Dictionary<KeyType, ValueType>  //或者

  [KeyType : ValueType]

注意:KeyType必须是hashable——即 It must provide a way to make itself uniquely representable. 所有的基本数据类型默认都是hashable,这些类型都可以作为字典的keys

可以这么初始化一个数组:

var dict = [KeyType: ValueType]()

3. 可变集合 Mutability of Collections

  3.1 可变数组与字典:将数组或字典定义为变量(variable),那么它是可变的,可以进行增删改,可以修改size

  

  将数组或字典定义为常量(constant),那么它的size不能被改变。定义为常量的字典和数组略有不同。

  3.2不可变字典: 1) 不能修改size

          2) 不能修改key的value

  3.3不可变数组: 1) 不能更改size

          2) 可以给已存在的index的value设置新值

参考 https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html#//apple_ref/doc/uid/TP40014097-CH8-ID105

原文地址:https://www.cnblogs.com/actionke/p/4200674.html