Joseph Campbell once said, “computers are like Old Testament gods: lots of rules and no mercy.”
好喜歡這句話。計(jì)算機(jī)像是舊時代的神,全部都是規(guī)則,沒有仁慈。一切都是按指定的規(guī)則運(yùn)行。所以,編程這件事,不就是在造神嘛??? 是不是有點(diǎn)熱血沸騰,又想敲代碼啦~
03 - Array Dictionary Set Enums
-
Array
創(chuàng)建一個數(shù)組
var scores = Array<Int>()
var albums = [String]()
var albums2 = ["Folklore"]
數(shù)組添加的數(shù)據(jù)類型需要是同一類型的。使用append方法添加。
var temperatures = [25.3, 28.2, 26.4]
var intTemp : Int = 0
// 不能添加不同類型
// temperatures.append("Chris")
// temperatures.append(intTemp)
temperatures.append(1) // 1會被自動轉(zhuǎn)成Double型
獲取數(shù)組元素個數(shù):.count
刪除數(shù)組指定元素:remove(at:)
刪除全部元素removeAll()
判斷數(shù)組是否包含某個元素contains()
對數(shù)組元素進(jìn)行排序sorted(),將返回一個新的數(shù)組
對數(shù)組元素進(jìn)行反轉(zhuǎn)reversed(),將返回一個新的數(shù)組
Tips:
當(dāng)反轉(zhuǎn)一個數(shù)組的時候,并不需要真的反轉(zhuǎn)整個數(shù)組。所以swift將數(shù)組包裝了一層ReversedCollection<Array<...>>,不要驚訝地發(fā)現(xiàn)它不再只是一個簡單的數(shù)組!
在賦給新的數(shù)組的時候,它會自動去除包裝的一層。
使用這種會產(chǎn)生新的數(shù)組的方法的時候,ed會產(chǎn)生一個新的數(shù)組,不加ed會直接在原數(shù)組上修改。例如sort()和sorted()
-
Dictionary
創(chuàng)建一個字典
var heights = [String: Int]()
let olympics = [
2012: "London"
]
字典取值可以加一個默認(rèn)值來拆包。
print(olympics[2012, default: "Unknown"])
獲取字典元素個數(shù):.count
刪除全部元素:removeAll()
-
Set
創(chuàng)建一個集合
var people = Set<String>()
// 這里要注意下,Set([...]) 中的"[ ]"
let people2 = Set(["Denzel Washington", "Tom Cruise", "Nicolas Cage", "Samuel L Jackson"])
將集合的元素排序后返回?cái)?shù)組:sorted()
添加一個元素:insert
獲取集合元素個數(shù):.count
判斷是否包含某個元素:contains()
Tips:集合相對于數(shù)組有一個特別大的優(yōu)點(diǎn),那就是查找速度特別快。不管集合中的元素有多大,
contains()方法能很快的得出結(jié)果。數(shù)組會遍歷元素。
-
Enum
定義一個枚舉類型的基本寫法
enum Weekday {
case monday
case tuesday
case wednesday
case thursday
case friday
}
或者,可以快速定義:
enum Weekday {
case monday, tuesday, wednesday, thursday, friday
}
Tips: 許多語言沒有枚舉也可以正常運(yùn)行。對于枚舉的存在,應(yīng)該是更好的避免書寫錯誤。比如,可以使用"monday", "tuesday","wednesday", "thursday", "friday"來區(qū)分類型,但是在使用的時候,很容易拼寫錯誤,或者忘記對應(yīng)的類型。