swift主要提供了三种集合类型,只有Array是有序的。
Mutability of Collections
使用 var
声明的集合就是可变的。如果集合是不变的,最后使用let
,有利于编译器优化代码,代码可读性也高。
Arrays
array把一些类型相同的值存在一个有序列表里。
Array Type Shorthand Syntax
swift 的数组完整写法是 Array<Element>, Element是array中允许存储的值类型。也可以使用[Element]的方式来创建array,这种方式是首选的。
var someInts = [Int]()
print("someInts is of type [Int] with \(someInts.count) items.")
someInts.append(3)
someInts = []
Creating an Array with a Default Value
var threeDoubles = Array(repeating: 0.0, count: 3)
// threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]
Creating an Array with an Array Literal
var shoppingList: [String] = ["Eggs", "Milk"]
// shoppingList has been initialized with two initial items
var shoppingList = ["Eggs", "Milk"]
Accessing and Modifying an Array
使用array的属性、方法或下标语法来修改或者获取一个数组。
shoppingList.isEmpty
shoppingList.append("Flour")
shoppingList += ["Baking Powder"]
var firstItem = shoppingList[0]
shoppingList[0] = "Six eggs"
shoppingList.insert("Maple Syrup", at: 0)
let mapleSyrup = shoppingList.remove(at: 0)
shoppingList.removeLast()
shoppingList[4...6] = ["Bananas", "Apples"]
shoppingList 的第 5、6、7个string被 “Bananas” 和 “Apples” 这两个string代替了,总个数减一。
Iterating Over an Array
for item in shoppingList {
print(item)
}
使用enumerated()
方法遍历数组,得到的是下表和item组成的元组。
for (index, value) in shoppingList.enumerated() {
print("Item \(index + 1): \(value)")
}
Sets
Set Type Syntax
与数组不同,set 没有[Element]语法(不能被编译器推测出类型),只能是 Set<Element>
。
Creating and Initializing an Empty Set
var letters = Set<Character>()
print("letters is of type Set<Character> with \(letters.count) items.")
// Prints "letters is of type Set<Character> with 0 items."
letters.insert("a")
// letters now contains 1 value of type Character
letters = []
// letters is now an empty set, but is still of type Set<Character>
Creating a Set with an Array Literal
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
虽软编译器不能退测出是Set类型,但是可以推测出Set内元素的类型。
var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]
Dictionary
swift中字典的keys类型相同,values也相同。
var namesOfIntegers = [Int: String]()
// namesOfIntegers is an empty [Int: String] dictionary
namesOfIntegers[16] = "sixteen"
// namesOfIntegers now contains 1 key-value pair。key = 16, value = "sixteen"
namesOfIntegers = [:]
// namesOfIntegers is once again an empty dictionary of type [Int: String]
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
airports["LHR"] = "London"
// the airports dictionary now contains 3 items
airports["LHR"] = "London Heathrow"
// the value for "LHR" has been changed to "London Heathrow"
if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
print("The old value for DUB was \(oldValue).")
}
updateValue(_:forKey:)
方法,如果不存在key,假如;如果存在则更新,并返回旧值。所以这个方法的返回值类型是optional的。下标语法也有这种效果。
if let airportName = airports["DUB"] {
print("The name of the airport is \(airportName).")
} else {
print("That airport is not in the airports dictionary.")
}
value = nil 时候,是移除这个键值对。
airports["APL"] = nil
// APL has now been removed from the dictionary
也可以使用方法:
if let removedValue = airports.removeValue(forKey: "DUB") {
print("The removed airport's name is \(removedValue).")
} else {
print("The airports dictionary does not contain a value for DUB.")
}
// Prints "The removed airport's name is Dublin Airport."
字典的for-in 每个item是(key,value)元组。
for (airportCode, airportName) in airports {
print("\(airportCode): \(airportName)")
}
也可以只看key或value
for airportCode in airports.keys {
print("Airport code: \(airportCode)")
}
取字典的所有key或value,使用数组返回。
let airportCodes = [String](airports.keys)
// airportCodes is ["YYZ", "LHR"]