swift學習記錄03-集合:數組、字典

一。數組集合
1.數組的聲明與初始化
聲明:var stdentList1: Array或者
var stdentList2: [String]
初始化:var studentList1: Array = [“4”,”3”,”2”,”1”]//可變
var studentList2: [String] = [“4”,”3”,”2”,”1”]//不可變
let studentList3: [String] = [“4”,”3”,”2”,”1”]//不可變,訪問效率上要比可變數組高,確定不變的最好用不可變數組
var studentList4 = String //空數組

2.數組的修改
var studentList : [String] = [“1”, “2”, “3”]
studentList.append(“4”) // 在數組後面加入元素:[“1”, “2”, “3”, “4”]
studentList += [“5”, “6”] //在數組後面添加數組:[“1”, “2”, “3”, “4”, “5”, “6”]
stuedntList.insert(“7”, adIndex:studentList.count)//在特定位置添加元素:[“1”, “2”, “3”, “4”, “5”, “6”, “7”]
let removeStu = stuedntList.removeAtIndex(0) //刪除第一個元素,並返回這個元素:removeStu = 1
stuedntList[0] = “0” //替換第一個元素 : [“0”, “3”, “4”, “5”, “6”, “7”]

3.數組的遍歷
推薦使用for in 進行遍歷
let studentList: [String] = [“1”, “2”, “3”]
for item in studentList {
println(item)
}
for (index, value) in enumerate(studentList){
println(“Item (index + 1) : (value)”)
}
運行結果:
1
2
3
Item 1 : 1
Item 2 : 2
Item 3 : 3
enumerate函數可以去除數組的索引和元素,(index, value)是元組類型

二、字典集合
1.字典聲明與初始化
var studentDictionary: Dictionary

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章