集合类型

Swift 语言提供 Arrays、Sets 和 Dictionaries 三种基本的集合类型用来存储集合数据。

  • 数组(Arrays)是有序数据的集。
  • 集合(Sets)是无序无重复数据的集。
  • 字典(Dictionaries)是无序的键值对的集。


    image.png
数组:
var someInts = [Int]()   //初始化数组
var someInts: [Int] = []
var shoppingList: [String] = ["Eggs", "Milk"]  //推荐该方式
集合:
var letters = Set()
letters.insert("a")

//用数组字面量创建集合
var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]
字典:
var namesOfIntegers = [Int: String]()
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

//字典遍历
for (airportCode, airportName) in airports {
    print("\(airportCode): \(airportName)")
}
for airportCode in airports.keys {
    print("Airport code: \(airportCode)")
}
// Airport code: YYZ
// Airport code: LHR
for airportName in airports.values {
    print("Airport name: \(airportName)")
}

你可能感兴趣的:(集合类型)