ch04集合类型
//swift提供和C类似的控制结构,比如for和while循环处理多任务,if,guard,switch语句执行不同的分支语句,break,continue改变执行的流程
//swift提供了两种for循环:for-in 和for //For-In for index in 1...5 { // print("\(index) times is \(index * 5)") } // 1 times 5 is 5 // 2 times 5 is 10 // 3 times 5 is 15 // 4 times 5 is 20 // 5 times 5 is 25 //被迭代序列是从1到5范围内的数字,包括1和5,使用闭合操作符... //index是一个常量,每次迭代开始的时候,它的值会自动被设置,在使用之前没必要去声明它,通过它的循环,它被模糊声明,所以没必要用let关键字声明 //如果你不需要序列中的每一个值,你可以使用下划线_代替变量名,来忽略这些值 let base = 3 let power = 10 var answer = 1 for _ in 1...power { answer *= base } //print("\(base) to the power of \(power) is \(answer).") // prints "3 to the power of 10 is 59049" //使用for-in循环来迭代数组的items let names = ["Anna", "Alex", "Brian", "Jack"] for name in names { // print("Hello, \(name)!") } // Hello, Anna! // Hello, Alex! // Hello, Brian! // Hello, Jack! //你也可以迭代字典,获得键值对,返回的值是(key,value)的元组 let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4] for (animalName, legCount) in numberOfLegs { // print("\(animalName)s have \(legCount) legs") } // ants have 6 legs // cats have 4 legs // spiders have 8 legs //字典里的item不会按原来的顺序被检索出来, //For //除了for-in循环,swift还提供了一种传统C的for循环 for var index = 0; index < 3; ++index { // print("index is \(index)") } // index is 0 // index is 1 // index is 2 //这种for循环的格式如下: //for <#initialization#>; <#condition#>; <#increment#> { // <#statements#> //} //常量或者变量在初始化的时候被声明,比如 var index = 0只作用在for循环 var index: Int for index = 0; index < 3; ++index { // print("index is \(index)") } // index is 0 // index is 1 // index is 2 //print("The loop statements were executed \(index) times") // prints "The loop statements were executed 3 times"
//swift提供了两种while循环 //While //如果条件为true,执行循环体,直到条件为false,停止执行 //格式如下: //while <#conditon#> { // <#statement#> //} //Repeat-While //格式如下: //repeat { //<#statement#> //} while <#condtion#> //区别:While是先判断条件是否成立,成立执行循环体,不成立执行循环体下面的语句,Repeat-While是先执行一次循环体,然后判断条件是否成立,如果条件成立,继续执行循环体,否则执行循环体后面的语句
//swift提供了两种条件分支,if和switch //If var temperatureInFahrenheit = 30 if temperatureInFahrenheit < 32 { // print("It's very cold. Consider wearing a scarf.") } // prints "It's very cold. Consider wearing a scarf." temperatureInFahrenheit = 40 //if temperatureInFahrenheit < 32 { // print("It's very cold. Consider wearing a scarf.") //} else { // print("It's not that cold. Wear a t-shirt.") //} // prints "It's not that cold. Wear a t-shirt." temperatureInFahrenheit = 90 //if temperatureInFahrenheit < 32 { // print("It's very cold. Consider wearing a scarf.") //} else if temperatureInFahrenheit >= 86 { // print("It's really warm. Don't forget to wear sunscreen.") //} else { // print("It's not that cold. Wear a t-shirt.") //} // prints "It's really warm. Don't forget to wear sunscreen." //Switch //格式如下: //switch <#some value to consider#> { //case <#value 1#>: // <#respond to value 1#> //case <#value 2#>, //<#value 3#>: // <#respond to value 2 or 3#> // default: // <#otherwise, do something else#> //} let someCharacter: Character = "e" //switch someCharacter { // case "a","e","i","o","u": // print("\(someCharacter) is a vowel.") //case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", //"n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z": // print("\(someCharacter) is a consonant") //default: // print("\(someCharacter) is not a vowel or a consonant") //} //对比C和OC的switch结构,swift的switch的结构在执行完语句并没有执行break //虽然break在swift中没有被要求,但是你仍然可以使用break //每一个case的体一定要至少含有一条可执行的语句,下面的写法是非法的,因为第一个case是空的 let anotherCharacter: Character = "a" //switch anotherCharacter { // case "a": // case "A": // print("The letter A") //default: // print("Not the letter A") //} // this will report a compile-time error //间隔匹配--Interval Matching let approximateCount = 62 let countedThings = "moons orbiting Saturn" var naturalCount: String switch approximateCount { case 0: naturalCount = "no" case 1..<5: naturalCount = "a few" case 5..<12: naturalCount = "several" case 12..<100: naturalCount = "dozens of" case 100..<1000: naturalCount = "hundreds of" default: naturalCount = "many" } //print("There are \(naturalCount) \(countedThings)") // prints "There are dozens of moons orbiting Saturn." //元组--Tuples let somePoint = (1,1) //switch somePoint { //case (0,0): // print("(0, 0) is at the origin") //case (_,0): // print("(\(somePoint.0),0) is on the x-axis") //case (0,_): // print("(0, \(somePoint.1)) is on the y-axis") //case (-2...2,-2...2): // print("(\(somePoint.0), \(somePoint.1)) is inside the box") //default: // print("(\(somePoint.0), \(somePoint.1)) is outside of the box") //} // prints "(1, 1) is inside the box" //值绑定--Value Bindings let anotherPoint = (2, 0) //switch anotherPoint { //case (let x, 0): // print("on the x-axis with an x value of \(x)") //case (0, let y): // print("on the y-axis with a y value of \(y)") //case (let x, let y): // print("somewhere else at (\(x), \(y))") //} // prints "on the x-axis with an x value of 2" //这个switch语句来判断点在x轴,还是在y轴,或者在其他地方 //说明:这个switch语句没有一个default case,因为(let x, let y)声明了一个元组,两个默认常量可能有的值,所以default case没必要在写了 //Where let yetAnotherPoint = (1, -1) //switch yetAnotherPoint { //case let (x, y) where x == y: // // print("(\(x), \(y)) is on the line x == y") //case let (x, y) where x == -y: // // print("(\(x), \(y)) is on the line x == -y") //case let (x, y): // // print("(\(x), \(y)) is just some arbitrary point") //} // prints "(1, -1) is on the line x == -y" //正如之前的例子,最后一个case包括了所有的可能,因此default case 没有必要写了
//swift提供了五种控制转移语句,continue,break,fallthrough,return,trow //Continue--结束本次循环执行下一次循环 let puzzleInput = "great minds think alike" var puzzleOutput = "" for character in puzzleInput.characters { switch character { case "a", "e", "i", "o", "u", " ": continue default: puzzleOutput.append(character) } } //print(puzzleOutput) // prints "grtmndsthnklk" //Break--结束循环,执行循环体外的语句 let numberSymbol: Character = "三" var possibleIntegerValue: Int? switch numberSymbol { case "1", "١", "一", "๑": possibleIntegerValue = 1 case "2", "٢", "二", "๒": possibleIntegerValue = 2 case "3", "٣", "三", "๓": possibleIntegerValue = 3 case "4", "٤", "四", "๔": possibleIntegerValue = 4 default: break } //if let integerValue = possibleIntegerValue { // print("The integer value of \(numberSymbol) is \(integerValue).") //} else { // print("An integer value could not be found for \(numberSymbol).") //} // prints "The integer value of 三 is 3." //语句跳转--Fallthrough //swift中的switch语句不能跳转到每一个case的底部,如果你真的需要C类型的跳转行为,你可以用falltrough关键字声明 let integerToDescribe = 5 var description = "The number \(integerToDescribe) is" switch integerToDescribe { case 2, 3, 5, 7, 11, 13, 17, 19: description += " a prime number, and also" fallthrough default: description += "an integer" } // prints "The number 5 is a prime number, and also an integer." //print(description) //说明:fallthrough关键字不会检查case的条件,这个关键字仅仅会导致代码执行直接移动到下一个case中的语句(或default case)块 //标签语句--Labeled Statements //格式如下: //<#label name#>: while <#condition#> { // <#statement#> //} let finalSquare = 25 var board = [Int](count: finalSquare + 1, repeatedValue: 0) board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02 board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08 var square = 0 var diceRoll = 0 gameLoop: while square != finalSquare { if ++diceRoll == 7 { diceRoll = 1 } switch square + diceRoll { case finalSquare: // diceRoll will move us to the final square, so the game is over break gameLoop case let newSquare where newSquare > finalSquare: // diceRoll will move us beyond the final square, so roll again continue gameLoop default: // this is a valid move, so find out its effect square += diceRoll square += board[square] } } //print("Game over!") //说明:如果break语句没有用gameLoop标签,那么将break out switch语句,而不是while语句,使用gameLoop 标签使控制结构更加清晰 //但调用continue gameLoop去跳转到下一次迭代的时候,没有必要使用gameLoop标签,因为这儿仅仅只有一个循环,因此continue语句会影响到循环是明确的,但是这儿continue语句使用gameLoop标签,是无害的
//guard语句,像if语句,执行语句依靠表达式的Bool值,为了使guard后面的语句被执行,你用guard语句要求条件一定是true,不像if语句,guard语句总是有一个else,如果条件为false,else里面的代码将会被执行 //func greet(person: [String: String]) { // guard let name = person["name"] else { // return // } // print("Hello \(name)!") // // guard let location = person["location"] else { // print("I hope the weather is nice near you.") // return // } // print("I hope the weather is nice in \(location).") //} // //greet(["name": "John"]) // prints "Hello John!" // prints "I hope the weather is nice near you." //greet(["name": "Jane", "location": "Cupertino"]) // prints "Hello Jane!" // prints "I hope the weather is nice in Cupertino."
if #available(iOS 9, OSX 10.10, *) { // Use iOS 9 APIs on iOS, and use OS X v10.10 APIs on OS X } else { // Fall back to earlier iOS and OS X APIs } //上面的availability条件制定特别的iOS,if语句里的仅仅在iOS 9或者稍后的版本,OS X v10.10或者稍后的版本 执行,最后一个参数*,要求运行在任何平台 //if #available(<#platform name#> <#version#>, <#...#>, *) { // // <#statements to execute if the APIs are available#> //} else { // // <#fallback statements to execute if the APIs are unavailable#> //}