在Swift中仍然保留了OC中的三種集合類型:
Array:數(shù)組是有序的值集合。
Set:集合是惟一值的無序集合。
Dictionary:字典是鍵值關(guān)聯(lián)的無序集合。

Arrays, sets, and dictionaries in Swift are always clear about the types of values and keys that they can store. This means that you cannot insert a value of the wrong type into a collection by mistake. It also means you can be confident about the type of values you will retrieve from a collection.
在Swift中,數(shù)組、集合和字典的值得數(shù)據(jù)類型很明確。這意味著您不能將錯誤類型的值插入到集合中。
它還意味著您可以對從集合中檢索到的值類型有信心。
Swift’s array, set, and dictionary types are implemented as generic collections.
Swift的數(shù)組、集合和字典類型被實現(xiàn)為泛型集合。
If you create an array, a set, or a dictionary, and assign it to a variable, the collection that is created will be mutable. This means that you can change (or mutate) the collection after it’s created by adding, removing, or changing items in the collection. If you assign an array, a set, or a dictionary to a constant, that collection is immutable, and its size and contents cannot be changed.
如果您創(chuàng)建一個數(shù)組、一個集合或一個字典,并將其賦值給一個變量,那么所創(chuàng)建的集合將是可變的。這意味著您可以通過在集合中添加、刪除或更改項目來更改(或更改)集合。如果您將數(shù)組、集合或字典賦值給常量,那么該集合是不可變的,它的大小和內(nèi)容不能被更改。
看到了官網(wǎng)對于Swift中集合的各種特性解釋,接下來我們進入實踐階段,來驗證它是否是這樣的。
Arrays
Arrays的初始化
在創(chuàng)建之初,我們首先要想好,是需要可變的還是不可變的。
一般來說我們使用不可變的會增加我們程序的安全性,避免了我們在編寫程序時無意中添加或者刪除了某值造成不好的效果,但系統(tǒng)卻沒有給出相應(yīng)的提示。
let someNumber = [3,42,5]
print(someNumber)
結(jié)果:
[3, 42, 5]
在這一段程序中,我們直接將3,42,5三個int類型的值加入到了someNumber數(shù)組中去了。
在這過程中swift還需要動態(tài)的去判斷值的類型。
所以我們也可以直接指定它的數(shù)據(jù)類型:
let someNumber:[Int] = [3,42,5]
這樣的一個好處就是我們可以很容易的去識別一個數(shù)組當中值得類型是否正確:
let someNumber:[Int] = [3,"Str",5]
當你這樣寫的時候,編譯就會發(fā)生錯誤,因為"Str"是String類型并不是Int類型,程序就會及時的給予你提示。
然而上面的方式其實是一種簡寫的方式,完整的寫法應(yīng)該如下所示:
let someInts = [Int](arrayLiteral: 3,3,5)
print(someInts)
let arrayInts = Array(arrayLiteral: "3","3","3")
print(arrayInts)
我們再看其他的初始化方式:
創(chuàng)建一個空的數(shù)組
var someInts = [Int]()
這里要注意的就是[Int]它的數(shù)據(jù)類型不能省.不然會報錯。
因為Swift中嚴格的數(shù)據(jù)類型控制??梢栽O(shè)想,這里沒有數(shù)據(jù)類型控制的話,那么我們在之后的追加元素的操作中,
追加了不同的數(shù)據(jù),而我們之前又沒有顯示的去設(shè)定它的數(shù)據(jù)類型,就會造成數(shù)據(jù)類型不可控的情況,這個在Swift并不被允許。
你可以通過append去追加元素(當然了,首先你的數(shù)組是個變量,而不是常量):
someInts.append(3)
同時,如果你已經(jīng)初始化完畢,那么你可以直接設(shè)定你的數(shù)組為空:
someInts = []
你可能會有疑問,為什么一開始的時候不能這樣設(shè)置為空呢?
因為在這里雖然你設(shè)為了空,someInts的數(shù)據(jù)類型還是Int,你仍然是無法去添加其他類型的值的。
var someInts = [Int]()
someInts.append(3)
someInts = []
someInts.append("string") //error:Cannot convert value of type 'String' to expected argument type 'Int'
print(someInts)
我們再看看其它的初始化方式:
let threeDoubles = Array(repeatElement(0.0, count: 3))
print(threeDoubles)
結(jié)果:
[0.0, 0.0, 0.0]
其實從參數(shù)名稱上我們就可以知道,我們創(chuàng)建了3個重復值用于數(shù)組的初始化。
repeatElement方法中可以填寫兩個參數(shù),一個是需要重復的數(shù)據(jù),count表示重復多少次。
我想,這是為了方便我們在特定情況下的初始化吧。
嗯,繼續(xù)看看別的初始化方式:
我們在使用的時候,默認的數(shù)據(jù)的類型的確是確保了我們的數(shù)據(jù)類型安全,但同時也限制了我們編程的靈活性。
在很多實際的運用場景中,一個數(shù)組集合中包含的并不可能只有一種數(shù)據(jù)類型的值,如果每一種都需要定義個數(shù)組來進行操作的話,也會增加開發(fā)成本。當然咯,這個還是根據(jù)具體的環(huán)境來決定成本的舍取性的。
那么如何去定義一個什么類型都可以存的數(shù)組呢?
let anyData = ["String",34,53] as [Any]
print(anyData)
結(jié)果:
["String", 34, 53]
通過結(jié)果我們可以看到,這樣定義的數(shù)組可以容納其他類型的值。
初始化我們大概了解了之后,我們還需要了解它的內(nèi)置方法:
Array的內(nèi)置方法
first 獲取第一個元素
var shopping_list = ["A","B","C","D"]
print(shopping_list.first)
結(jié)果:
"A"
first where 根據(jù)判斷條件返回結(jié)果
var shopping_list = [53,4,2,45]
let result = shopping_list.first(where: { (intResult) -> Bool in
return intResult==54
})
print(result ?? 0)
這里的意思是如果第一個元素是54,那么返回正確結(jié)果,如果不是的話本來是應(yīng)該返回nil的,但是我們給它做了判斷,如果為nil,那么結(jié)果為0。
last 獲取最后一個元素
var shopping_list = ["A","B","C","D"]
print(shopping_list.last)
結(jié)果:
"D"
count 數(shù)量
let shopping_list = [3,4,2,3]
print("The shopping_list list contains \(shopping_list.count) items.")
結(jié)果:
The shopping_list list contains 4 items.
isEmpty 判空
let shopping_list = [3,4,2,3]
if shopping_list.isEmpty {
print("The shopping_list list is empty.")
} else {
print("The shopping_list list is not empty.")
}
結(jié)果:
The shopping_list list is not empty.
contains 判斷數(shù)組中是否包含某個元素
var shopping_list = ["A","B","C","D"]
print(shopping_list.contains("C"))
結(jié)果:
true
append 追加
var shopping_list = [1]
shopping_list.append(4)
print(shopping_list)
結(jié)果:
[1,4]
insert(newElement: at: ) 插入單個元素
將新元素插入到指定的位置,但不能插入到數(shù)組最后一位的下一位。
var shopping_list = [1]
shopping_list .insert(3, at: 1)
print(shopping_list)
結(jié)果:
[1,3]
insert(contentsOf:at:) 插入整個集合
var shopping_list = [1,2]
var otherShopping_list = [3,4,5]
shopping_list.insert(contentsOf: otherShopping_list, at: 2)
print(shopping_list)
結(jié)果:
[1,2,3,4,5]
replaceSubrange(Range<Int>, with: Collection) 將某個范圍的元素替換為指定的集合
var shopping_list = ["A","B","C","D"]
shopping_list.replaceSubrange(0...1,with:["F","E"])
print(shopping_list)
結(jié)果:
["F","E","C","D"]
remove(at:) 移除某個下標的元素
var shopping_list = [1,2,3,4]
shopping_list.remove(at: 0)
print(shopping_list)
結(jié)果:
[2,3,4]
removeFirst(count) 從開始位置開始移除指定數(shù)量的元素
var shopping_list = [1,2,3,4]
shopping_list.removeFirst(2)
print(shopping_list)
結(jié)果:
[3,4]
removeLast(count) 從末尾位置開始向前移除指定數(shù)量的元素
var shopping_list = [1,2,3,4]
shopping_list.removeLast(2)
print(shopping_list)
removeFirst() 移除第一個元素
var shopping_list = [1,2,3,4]
shopping_list.removeFirst()
print(shopping_list)
結(jié)果:
[2,3,4]
removeLast() 移除最后一個元素
var shopping_list = [1,2,3,4]
shopping_list.removeLast()
print(shopping_list)
結(jié)果:
[1,2,3]
removeSubrange(Range) 移除某個范圍內(nèi)的元素
var shopping_list = [1,2,3,4]
shopping_list.removeSubrange(0...1)
print(shopping_list)
結(jié)果:
[3,4]
0...1 表示 [0,1] 的區(qū)間,即包含0和1的范圍
removeAll() 移除所有
var shopping_list = [1,2,3,4]
shopping_list. removeAll()
print(shopping_list)
結(jié)果:
[]
移除數(shù)組中全部元素,有一個可選參數(shù),keepCapacity。如果keepCapacity = YES的話,那么數(shù)組移除元素后,其存儲空間還是存在的,在此往里存儲值,不需再給他分配存儲空間了。如果keepCapacity=NO的話,那么數(shù)組的存儲空間就會被回收掉。
var shopping_list = [1,2,3,4]
shopping_list. removeAll(keepCapacity: true)
print(shopping_list)
結(jié)果:
[]
數(shù)組的遍歷
比較常見的就是for-loop遍歷了。
var shopping_list = [1,2,3,4]
for item in shopping_list {
print(item, terminator: "")
}
結(jié)果:
1234
還有一種方式是枚舉遍歷法,我們有時也會稱之為迭代器遍歷
官網(wǎng)中這樣解釋到:
If you need the integer index of each item as well as its value, use the enumerated() method to iterate over the array instead. For each item in the array, the enumerated() method returns a tuple composed of an integer and the item. The integers start at zero and count up by one for each item; if you enumerate over a whole array, these integers match the items’ indices. You can decompose the tuple into temporary constants or variables as part of the iteration:
如果您需要這個項目的每一個值和索引,那么可以使用enumerated()方法來迭代該數(shù)組。對于數(shù)組中的每個項,enumerated()方法返回一個由一個整數(shù)和項組成的元組。整數(shù)從零開始,每一項都是一;如果您對整個數(shù)組進行枚舉,那么這些整數(shù)將匹配項目的索引。您可以將元組分解為臨時常量或變量,作為迭代的一部分:
var shopping_list = ["A","B","C","D"]
let enumerated_list = shopping_list.enumerated()
for (index, value) in enumerated_list {
print("Item \(index + 1): \(value)")
}
結(jié)果:
Item 1: A
Item 2: B
Item 3: C
Item 4: D
其中可以看到index就是它的索引,value是它的值。
sorted 排序
var shopping_list = [53,4,2,45]
for item in shopping_list.sorted(){
print(item,terminator: " ")
}
結(jié)果:
2 4 45 53
sorted by 有條件的排序
var shopping_list = [53,4,2,45]
shopping_list = shopping_list.sorted { (old, new) -> Bool in
return old<new;
}
print(shopping_list)
如果old<new為升序:
[2, 4, 45, 53]
old>new為降序:
[53, 45, 4, 2]