Swift 语言之集合类型学习笔记

数组

创建空的数组:

1
2
3
var someInts = [Int]()
println("someInts is of type [Int] with \(someInts.count) items.")
// prints "someInts is of type [Int] with 0 items."

添加数组数据项:

1
2
3
4
someInts.append(3)
// someInts now contains 1 value of type Int
someInts = []
// someInts is now an empty array, but is still of type [Int]

创建重复数据项的数组:

1
2
var threeDoubles = [Double](count: 3, repeatedValue: 0.0)
// threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]

数组相加:

1
2
3
4
5
var anotherThreeDoubles = [Double](count: 3, repeatedValue: 2.5)
// anotherThreeDoubles is inferred as [Double], and equals [2.5, 2.5, 2.5]

var sixDoubles = threeDoubles + anotherThreeDoubles
// sixDoubles is inferred as [Double], and equals [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]

数组字面量

1
2
var shoppingList: [String] = ["Eggs", "Milk"]
// shoppingList has been initialized with two initial items

读取和修改数组

数组数据项个数:

1
2
println("The shopping list contains \(shoppingList.count) items.")
// prints "The shopping list contains 2 items."

判断数组是否为空:

1
2
3
4
5
6
if shoppingList.isEmpty {
println("The shopping list is empty.")
} else {
println("The shopping list is not empty.")
}
// prints "The shopping list is not empty."

数组后面添加新的数据项:

1
2
shoppingList.append("Flour")
// shoppingList now contains 3 items, and someone is making pancakes

加法赋值运算符添加数据项:

1
2
3
4
shoppingList += ["Baking Powder"]
// shoppingList now contains 4 items
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
// shoppingList now contains 7 items

下标读取数组中的数据项:

1
2
var firstItem = shoppingList[0]
// firstItem is equal to "Eggs"

下标修改数组中的数据项:

1
2
shoppingList[0] = "Six eggs"
// the first item in the list is now equal to "Six eggs" rather than "Eggs"

下标修改数组中的一系列数据项:

1
2
shoppingList[4...6] = ["Bananas", "Apples"]
// shoppingList now contains 6 items

某个具体索引值之前添加数据项:

1
2
3
shoppingList.insert("Maple Syrup", atIndex: 0)
// shoppingList now contains 7 items
// "Maple Syrup" is now the first item in the list

删除某个特定索引值的数据项,并返回这个数据项:

1
2
3
4
let mapleSyrup = shoppingList.removeAtIndex(0)
// the item that was at index 0 has just been removed
// shoppingList now contains 6 items, and no Maple Syrup
// the mapleSyrup constant is now equal to the removed "Maple Syrup" string

删除最后一个数据项:

1
2
3
4
let apples = shoppingList.removeLast()
// the last item in the array has just been removed
// shoppingList now contains 5 items, and no apples
// the apples constant is now equal to the removed "Apples" string

遍历数组

1
2
3
4
5
6
7
8
for (index, value) in enumerate(shoppingList) {
println("Item \(index + 1): \(value)")
}
// Item 1: Six eggs
// Item 2: Milk
// Item 3: Flour
// Item 4: Baking Powder
// Item 5: Bananas

集合

创建空的集合:

1
2
3
var letters = Set<Character>()
println("letters is of type Set<Character> with \(letters.count) items.")
// prints "letters is of type Set<Character> with 0 items."

插入集合数据项:

1
2
3
4
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>

集合字面量

1
2
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
// favoriteGenres has been initialized with three initial items

读取和修改集合

集合元素个数:

1
2
println("I have \(favoriteGenres.count) favorite music genres.")
// prints ""I have 3 favorite music genres.""

判断集合是否为空:

1
2
3
4
5
6
if favoriteGenres.isEmpty {
println("As far as music goes, I'm not picky.")
} else {
println("I have particular music preferences.")
}
// prints "I have particular music preferences."

向集合中添加新的数据项:

1
2
favoriteGenres.insert("Jazz")
// favoriteGenres now contains 4 items

删除某个数据项,并返回这个数据项:

1
2
3
4
5
6
if let removedGenre = favoriteGenres.remove("Rock") {
println("\(removedValue)? I'm over it.")
} else {
println("I never much cared for that.")
}
// prints "Rock? I'm over it."

判断集合是否包含某个数据项:

1
2
3
4
5
6
if favoriteGenres.contains("Funk") {
println("I get up on the good foot.")
} else {
println("It's too funky in here.")
}
// prints "It's too funky in here."

遍历集合

使用for-in循环遍历集合:

1
2
3
4
5
6
for genre in favoriteGenres {
println("\(value)")
}
// Classical
// Jazz
// Hip hop

集合排序:

1
2
3
4
5
6
for genre in sorted(favoriteGenres) {
println("\(genre)")
}
// prints "Classical"
// prints "Hip hop"
// prints "Jazz"

字典

创建空的字典:

1
2
var namesOfIntegers = [Int: String]()
// namesOfIntegers is an empty [Int: String] dictionary

添加字典数据项:

1
2
3
4
namesOfIntegers[16] = "sixteen"
// namesOfIntegers now contains 1 key-value pair
namesOfIntegers = [:]
// namesOfIntegers is once again an empty dictionary of type [Int: String]

字典字面量

1
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

读取和修改字典

字典数据项个数:

1
2
println("The airports dictionary contains \(airports.count) items.")
// prints "The airports dictionary contains 2 items."

判断字典是否为空:

1
2
3
4
5
6
if airports.isEmpty {
println("The airports dictionary is empty.")
} else {
println("The airports dictionary is not empty.")
}
// prints "The airports dictionary is not empty."

字典后面添加新的数据项:

1
2
airports["LHR"] = "London"
// the airports dictionary now contains 3 items

下标修改字典中的数据项:

1
2
airports["LHR"] = "London Heathrow"
// the value for "LHR" has been changed to "London Heathrow"

updateValue(_:forKey:) 方式修改字典中的数据项:

1
2
3
4
if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
println("The old value for DUB was \(oldValue).")
}
// prints "The old value for DUB was Dublin."

下标判断字典中是否存在某个数据项:

1
2
3
4
5
6
if let airportName = airports["DUB"] {
println("The name of the airport is \(airportName).")
} else {
println("That airport is not in the airports dictionary.")
}
// prints "The name of the airport is Dublin Airport."

通过下标删除字典中的某个数据项:

1
2
3
4
airports["APL"] = "Apple International"
// "Apple International" is not the real airport for APL, so delete it
airports["APL"] = nil
// APL has now been removed from the dictionary

removeValueForKey(_:) 方式删除字典中的数据项:

1
2
3
4
5
6
if let removedValue = airports.removeValueForKey("DUB") {
println("The removed airport's name is \(removedValue).")
} else {
println("The airports dictionary does not contain a value for DUB.")
}
// prints "The removed airport's name is Dublin Airport."

遍历字典

键值对同时遍历:

1
2
3
4
5
6
7
8
for (index, value) in enumerate(shoppingList) {
println("Item \(index + 1): \(value)")
}
// Item 1: Six eggs
// Item 2: Milk
// Item 3: Flour
// Item 4: Baking Powder
// Item 5: Bananas

遍历字典的keys或values:

1
2
3
4
5
6
7
8
9
10
11
for airportCode in airports.keys {
println("Airport code: \(airportCode)")
}
// Airport code: YYZ
// Airport code: LHR

for airportName in airports.values {
println("Airport name: \(airportName)")
}
// Airport name: Toronto Pearson
// Airport name: London Heathrow

返回字典的keys或values数组:

1
2
3
4
5
let airportCodes = [String](airports.keys)
// airportCodes is ["YYZ", "LHR"]

let airportNames = [String](airports.values)
// airportNames is ["Toronto Pearson", "London Heathrow"]
坚持原创技术分享,您的支持将鼓励我继续创作!