## ARRAYS,DICTIONARIES,LOOPS,SWITCH CASE
* 通過類型注釋(Type annotaions)可以申明數組內容的類型:
~~~
var songs: [String] = ["Shake it Off", "You Belong with Me", "Back to December", 3]
//以上會報錯,因為數組內有非 String 類型的”3”在內。
~~~
* 以下代碼僅僅是聲明了一個將要被分配包含String對象數組的變量:
~~~
var array:[String]
//沒有真正創建數組對象
var array: [String] = []
//這時才是創建了數組對象
var array = [String] ()
//效果同上,語法更為簡潔。
~~~
* 數組可以直接使用”+”運算符結合:
~~~
var songs = ["Shake it Off", "You Belong with Me", "Love Story"]
var songs2 = ["Today was a Fairytale", "White Horse", "Fifteen"]
var both = songs + songs2
both += [“Everything”]
//可以增加并賦值
~~~
* 創建一個 Disctionary:
~~~
var person = [
"first": "Taylor",
"middle": "Alison",
"last": "Swift",
"month": "December",
"website": "taylorswift.com"
]
~~~
* Swift 中,條件表達式不需要括號:
~~~
if person == "hater" {
action = "hate"
} else if person == "player" {
action = "play"
} else {
action = "cruise"
}
~~~
* `在 Swift 2.0中,println() 改為 print()`
* Swift 的 for 循環語法:
~~~
// closed range operator
for i in 1...10{
println("\(i) x 10 is \(i * 10)")
}
/*
以上結果相當于:
println("1 x 10 is \(1 * 10)")
println("2 x 10 is \(2 * 10)")
println("3 x 10 is \(3 * 10)")
println("4 x 10 is \(4 * 10)")
println("5 x 10 is \(5 * 10)")
println("6 x 10 is \(6 * 10)")
println("7 x 10 is \(7 * 10)")
println("8 x 10 is \(8 * 10)")
println("9 x 10 is \(9 * 10)")
println("10 x 10 is \(10 * 10)")
*/
~~~
* 不需要「循環數」時也可以用下劃線代替:
~~~
for _ in 1 ... 5 {
str += " fake"
}
~~~
* half open range operator(半開區間運算符):“..<",例如 ..<5 將會循環四次,count 將會是 1,2,3,4。”..<“ 可以方便于遍歷數組(數組的 index 從0算起):
~~~
for i in 0 ..< count(people) {
println("\(people[i]) gonna \(actions[i])")
}
~~~
* 遍歷數組的語法:
~~~
...
for song in songs {
println("My favorite song is \(song)")
}
//通過 index 同時遍歷倆數組:
var people = ["players", "haters", "heart-breakers", "fakers"]
var actions = ["play", "hate", "break", "fake"]
for i in 0 ... 3 {
println("\(people[i]) gonna \(actions[i])")
}
~~~
* `獲取數組內的對象數量的方法在 Swift 1.2中是 count(array),在 Swift 2.0中是 array.count。`
* loop 中的 continue 語法 將會終止當前的迭代回到 loop 的開頭繼續迭代。
* switch/case 語法可以簡化較多的 if/else if 語法,Swift 要求 switch 條件變量所有可能的情況都得涵蓋( cases should exhustive),否則 Xcode 可能無法構建應用,default 可以避免該問題。
* 可以在 switch/case 中使用 “…”(half open range operator) 將變量可能的范圍作為一個 case:
~~~
let studioAlbums = 5
switch studioAlbums {
case 0...1:
println("You're just starting out")
case 2...3:
println("You're a rising star")
case 4...5:
println("You're world famous!")
default:
println("Have you done something new?")
}
~~~
* `Swift 2.0 方法調用和1.2稍有不同,需要寫明參數名,目的是提高代碼可讀性:`
~~~
func printAlbumRelease(name: String, year: Int) {
println("\(name) was released in \(year)")
}
printAlbumRelease("Fearless", year: 2008)
printAlbumRelease("Speak Now", year: 2010)
printAlbumRelease("Red", year: 2012)
~~~
* “->"符號為方法聲明返回值:
~~~
func albumsIsTaylor(name: String) -> Bool
~~~