Swift 整理(四)——控制流、函数、闭包

  • 控制流:for-in、while、Repeat-While、if、switch
 let someCharacter: Character = "z"
 switch someCharacter {
case "a":
     print("The first letter of the alphabet")
 case "z":
     print("The last letter of the alphabet")
 default:
     print("Some other character")
}
// 输出 "The last letter of the alphabet"
let anotherCharacter: Character = "a"
 switch anotherCharacter {
 case "a", "A":
     print("The letter A")
 default:
     print("Not the letter A")
 }
// 输出 "The letter A
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).") // 输出 "There are dozens of moons orbiting Saturn."
//元组
 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")
 }
// 输出 "(1, 1) is inside the box"
//值绑定:
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, y):
     print("somewhere else at (\(x), \(y))")
 }
// 输出 "on the x-axis with an x value of 2"
//用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")
}
// 输出 "(1, -1) is on the line x == -y"
//贯穿:和C语言一样执行下一个case
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."
 }
print(description)
// 输出 "The number 5 is a prime number, and also an integer."
  • 转移语句:continue、break、fallthrough、return、throw、guard-else
    continue:继续执行下一次循环
    break:结束循环
    fallthrough:贯穿,在switch中,可以执行下一个case
    return:返回函数
    throw:错误抛出
    guard-else:提前退出
//标签:
 gameLoop: while square != finalSquare {
     diceRoll += 1
     if diceRoll == 7 { diceRoll = 1 }
     switch square + diceRoll {
     case finalSquare:
// 骰子数刚好使玩家移动到最终的方格里,游戏结束。
         break gameLoop
     case let newSquare where newSquare > finalSquare:
// 骰子数将会使玩家的移动超出最后的方格,那么这种移动是不合法的,玩家需要重新掷骰子
         continue gameLoop
     default:
// 合法移动,做正常的处理 square += diceRoll
square += board[square]
} }
 print("Game over!")
  • 函数:func 是一段完成特定任务的独立代码片段。
//可选元组返回类型
func minMax(array: [Int]) -> (min: Int, max: Int)? {
     if array.isEmpty { return nil }
     var currentMin = array[0]
     var currentMax = array[0]
     for value in array[1..<array.count] {
         if value < currentMin {
             currentMin = value
         } else if value > currentMax {
             currentMax = value
         }
}
     return (currentMin, currentMax)
 }
//
 if let bounds = minMax(array: [8, -6, 2, 109, 3, 71]) {
     print("min is \(bounds.min) and max is \(bounds.max)")
}
// 打印 "min is -6 and max is 109"
//
//可变参数的func(1个、2个、3个....)
func arithmeticMean(_ numbers: Double...) -> Double {
     var total: Double = 0
     for number in numbers {
         total += number
     }
     return total / Double(numbers.count)
 }
arithmeticMean(1, 2, 3, 4, 5)
// 返回 3.0, 是这 5 个数的平均数。 arithmeticMean(3, 8.25, 18.75)
// 返回 10.0, 是这 3 个数的平均数。
//
//函数类型作为参数类型:
func stepForward(_ input: Int) -> Int {
     return input + 1
 }
 func stepBackward(_ input: Int) -> Int {
     return input - 1
 }
func chooseStepFunction(backward: Bool) -> (Int) -> Int {
     return backward? stepBackward : stepForward
//用 chooseStepFunction(backward:) 来获得两个函数其中的一个
}
var currentValue = 3
let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)
// moveNearerToZero 现在指向 stepBackward() 函数。
  • 闭包:自包含的函数代码块。
    三种形式的闭包:
  • 全局函数是一个有名字但不会捕获任何值的闭包
  • 嵌套函数是一个有名字并可以捕获其封闭函数域内值的闭包
  • 闭包表达式是一个利用轻量级语法所写的可以捕获其上下文中变量常量值的匿名闭包

闭包表达式:

//sorted方法:
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
func backward(_ s1: String, _ s2: String) -> Bool {
    return s1 > s2
}
var reversedNames = names.sorted(by: backward)
// reversedNames 为 ["Ewa", "Daniella", "Chris", "Barry", "Alex"]
//转成闭包表达式:
 reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in
     return s1 > s2
})
//根据上下文推断类型
reversedNames = names.sorted(by: { s1, s2 in return s1 > s2 } )
//单表达式闭包隐式返回
reversedNames = names.sorted(by: { s1, s2 in s1 > s2 } )

尾随闭包:

func someFunctionThatTakesAClosure(closure: () -> Void) { 
// 函数体部分
}
// 以下是不使用尾随闭包进行函数调用
someFunctionThatTakesAClosure(closure: {
// 闭包主体部分 
})
// 以下是使用尾随闭包进行函数调用
someFunctionThatTakesAClosure() {
// 闭包主体部分 
}

捕获值:

func makeIncrementer(forIncrement amount: Int) -> () -> Int {
    var runningTotal = 0
    func incrementer() -> Int {
        runningTotal += amount
        return runningTotal
    }
    return incrementer
}

逃逸闭包:@escaping

var completionHandlers: [() -> Void] = []
func someFunctionWithEscapingClosure(completionHandler: @escaping () -> Void) {
    completionHandlers.append(completionHandler)
}

自动闭包:@autoclosure
一种自动创建的闭包,用于包装传递给函数作为参数的表达式。不接受任何参数,当它被调用的时候,会返回被包装在其中的表达式的值。

//延时求值:
var customersInLine = ["Chris", "Alex", "Ewa", "Barry", "Daniella"] print(customersInLine.count)
// 打印出 "5"
let customerProvider = { customersInLine.remove(at: 0) } print(customersInLine.count)
// 打印出 "5"
print("Now serving \(customerProvider())!") // Prints "Now serving Chris!" print(customersInLine.count)
// 打印出 "4"
//
// customersInLine is ["Ewa", "Barry", "Daniella"]
 func serve(customer customerProvider: @autoclosure () -> String) {
     print("Now serving \(customerProvider())!")
 }
serve(customer: customersInLine.remove(at: 0)) // 打印 "Now serving Ewa!"
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容

  • SwiftDay011.MySwiftimport UIKitprintln("Hello Swift!")var...
    smile丽语阅读 3,806评论 0 6
  • Swift 介绍 简介 Swift 语言由苹果公司在 2014 年推出,用来撰写 OS X 和 iOS 应用程序 ...
    大L君阅读 3,128评论 3 25
  • 86.复合 Cases 共享相同代码块的多个switch 分支 分支可以合并, 写在分支后用逗号分开。如果任何模式...
    无沣阅读 1,272评论 1 5
  • Linux sed命令是利用script来处理文本文件。 sed可依照script的指令,来处理、编辑文本文件。 ...
    金星show阅读 343评论 0 0
  • 这种黑白颠倒的生活方式已经持续了半个月。每天从夕阳开始工作。凌晨四点的时候关掉房间的灯,等待着日出,直到天空完全明...
    斯莫阅读 173评论 0 1