Swift學習之十二:控製流
/* 控製流 for for-in while do-while */ let count = 5 for var i = 0; i < count; i++ { print("\(i)") } for i in 0..count { print("\(i)") } let base = 4 let power = 10 var answer = 1 // 使用_來忽略某個值 for _ in 1...power { answer *= base } // 訪問數組 let names = ["Anna", "Alex", "Brian", "Jack"] for name in names { println("Hello, \(name)") } // 訪問字典 let numberOfLegs = ["spider" : 8, "ant" : 6, "cat" :4] for (key, value) in numberOfLegs { println("\(key)s have \(value) legs") } // 循環遍曆字符串 for c in "Hello" { print(c) } var index: Int for index = 0; index < 4; ++index { println("Index is \(index)") } // while循環 let times = 10 var count = 0 while count < times { print("\(count++)") } // do-while循環 let times = 10 var count = 0 do { count++ println("\(count)") } while count < times // switch 語句在swift中與C和OC中是不同的,在Swift中匹配到一個Case後,不需要添加break, // 也會在執行完匹配的那一項後自動Break。 let c = "a" switch c { case "a" : print("a") case "b" : print("b") case "c" : print("c") default: print("default") } // print a // 範圍匹配 let count = 1_000_000 var msg: String switch count { case 0: msg = "no" case 1...3: msg = "a few" case 10...99: msg = "lower than one hundred" case 100...999: msg = "lower than one thousand" case 1000...9999: msg = ”lower than then thousand“ case 10000...99999: msg = "lower than one million" default: msg = "no value" }
最後更新:2017-04-03 07:57:03