ARRAYS,DICTIONARIES,LOOPS,SWITCH CASE

最后更新于:2022-04-01 04:44:25

## 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 ~~~
';