转载

OS初探: Swift 2.2控制流与函数闭包

Control Flow

Swift通过 ifswitch 实现条件选择,通过 for-inforwhilerepeat-while 实现循环控制。

if语句中,条件必须为Boolean表达式。缺失值的处理可通过 let?? 实现。

var optionalName: String? = "J A" var greeting = "Hello!" if let name = optionalName {     greeting = "Hello, /(name)" }   let nickName: String? = nil let fullName: String = "J A" let informalGreeting = "Hi /(nickName ?? fullName)" 

switch语句支持任何类型数据间的广义比较。下例便涉及了常量间的模式匹配。

let vegetable = "red pepper" switch vegetable { case "cucumber", "watercress": print("That sounds good.") case let x where x.hasSuffix("pepper"): print("Is it a spicy /(x)?") default: print("Everything tastes good.") } 

与C相比,Swift的 switch 语句执行完匹配的分支后,不会再跳转到下一分支,因而无需显式声明break。

for-in语句用于词典内元素遍历。由于词典这一数据结构属于无序集合,故键值的遍历并无固定次序。需要保证次序时,可通过 ..< (开区间)或 ... (闭区间)指定索引区间。

let interestingNumbers = [   "Prime": [2, 3, 5, 7, 11, 13],   "Fibonacci": [1, 1, 2, 3, 5, 8],   "Square": [1, 4, 9, 16, 25], ] var largest = 0 for (kind, numbers) in interestingNumbers {   for number in numbers {     if number > largest {       largest = number     }   } } 

while语句可用于描述:满足特定条件时,重复执行的代码块。保证循环至少执行一次的情况下,循环条件需放于语句尾部。

var n = 2 repeat {   n = n * 2 } while n < 100 print(m) 

Functions and Closures

Swift的函数声明中明显有go的影子。函数的多返回值可通过元组创建复合值,从而通过名或序引用元组元素。函数可传递数组参数。嵌套函数中,内函数可使用外函数声明变量。与C不同,Swift的函数是一种first-class类型(即,可作为函数返回值,可作为函数参数,运行时创建),是闭包的一种特例。

func greet(name: String, day:String) -> String {   return "Hello /(name), today is /(day)." } greet("Bob", day:"Tuesday")  func calculateStatistics(scores:[Int]) -> (min:Int, max:Int, sum:Int) {   var min = scores[0]   var max = scores[0]   var sum = 0   for score in scores {     if score > max { max = score }     else if score < min { min = score }     sum += score   } return (min, max, sum) }  var numbers = [20, 19, 7, 12] numbers.map({   (number:Int) -> Int in     let result=3*number    return result }) //numbers.map({ number in 3*number }) //numbers.sort { $0 > $1} 
原文  http://www.ituring.com.cn/article/217666
正文到此结束
Loading...