Swift 中的集合有三類:
- 數(shù)組(Arrays)
- 集合(Sets)
- 字典(Dictionaries)
三種集合用以存儲(chǔ)集合數(shù)據(jù)。數(shù)組是有序數(shù)據(jù),集合是無(wú)序無(wú)重復(fù)數(shù)據(jù)集,字典是無(wú)序的鍵值對(duì)集。這個(gè)表很很能說(shuō)明問(wèn)題(來(lái)自于《The Swift Programming Language 中文版》):
(img)
??
集合是可變的,但如果創(chuàng)建的是一個(gè)常量的集合,則不能修改集合內(nèi)的數(shù)據(jù)。集合中數(shù)據(jù)的類弄必須是明確的。
//: [Previous](@previous)
import Foundation
//: ## 數(shù)組
// 組建一個(gè)空數(shù)組
var someInts = [Int]() // 通過(guò)賦值,someInts被推斷為[Int]類型的數(shù)組
someInts.count // output: 0
// 創(chuàng)建一個(gè)帶有默認(rèn)值的數(shù)組
var threeDoubles = [Double](count: 3, repeatedValue: 0.0)
// 相種存在數(shù)據(jù)的相同類型數(shù)據(jù)可進(jìn)行相加
// 可用字面量構(gòu)造數(shù)組,類型相同,數(shù)組類型會(huì)被自動(dòng)推導(dǎo)出來(lái)
var twoDoubles = [2.4, 2.5]
var fiveDoubles = threeDoubles + twoDoubles
print(fiveDoubles.count)
// output: 5
// 可使用布爾值屬性 isEmpty 作數(shù)據(jù)數(shù)量作檢查
someInts.isEmpty
fiveDoubles.isEmpty
// 使用append(_:)方法在數(shù)組后面添加新的同類型數(shù)據(jù)項(xiàng)
someInts.append(5)
print(someInts) // output: [5]
// 使用下標(biāo)來(lái)獲取數(shù)組中的數(shù)據(jù)項(xiàng)
var firstItem = fiveDoubles[0]
// 可使用下查來(lái)修改數(shù)據(jù)項(xiàng)的值
fiveDoubles[0] = 10
print(fiveDoubles) // output: [10, 0, 0, 2.4, 2.5]
// 使用insert(_:atIndex:)在某個(gè)具體索引位置之前添加數(shù)據(jù)
fiveDoubles.insert(20.0, atIndex: 0)
print(fiveDoubles) // output: [20.0, 10.0, 0.0, 0.0, 2.4, 2.5]
// 使用removeAtIndex(_:)除索引項(xiàng)數(shù)據(jù)
fiveDoubles.removeAtIndex(0)
print(fiveDoubles.count) // output: 5
// 數(shù)組遍歷 使用用語(yǔ)法 for-in 來(lái)進(jìn)行
for i in fiveDoubles {
print("Item: \(i)")
}
//
//Item: 10.0
//
//Item: 0.0
//
//Item: 0.0
//
//Item: 2.4
//
//Item: 2.5
//: ## 集合
// 創(chuàng)建一個(gè)Character類型的集合
var letters = Set<Character>()
letters.insert("B")
//
var stringSet: Set = ["aaaa", "aaaa", "bbbb"]
print("集合中的數(shù)據(jù)條數(shù):\(stringSet.count), 分別是:\(stringSet)")
// 集合中的數(shù)據(jù)條數(shù):2, 分別是:["bbbb", "aaaa"]
// 集合數(shù)據(jù)沒(méi)有順序之分,但卻不能重復(fù)。
// 在數(shù)據(jù)輸出這時(shí)卻是可以作一個(gè)輸出上的排序
for str in stringSet.sort() {
print("item: \(str)")
}
//item: aaaa
//
//item: bbbb
//: ## 字典
var nameOfItegers = [Int: String]()
// nameOfItegers 是一個(gè)空的 [Int: String] 字典
nameOfItegers[16] = "sixteen" // 添加值
nameOfItegers = [:] // 清空
// 和數(shù)組一樣,也可以根據(jù)字面量來(lái)構(gòu)造字典
let student = ["張三": "001", "李四": "002"] // 類型:[String : String]
// 取值可使用索引鍵即可
let zhansan = student["張三"]
// 如果鍵值不存在,則直接返回nil
if let name = student["Andy"] {
print("name: \(name)")
} else {
print("名稱不在字典里")
}
//名稱不在字典里
// 字典的遍歷可使用 for-in ,值是(key, value) 的形式
for (name, number) in student {
print("Name: \(name), Number: \(number)")
}
//Name: 張三, Number: 001
//Name: 李四, Number: 002