swiftiOS Dev.iOS Developer

Swift 学习笔记 - 函数与闭包

2016-10-21  本文已影响190人  酷酷的哀殿

函数

var mathFunction: (Int, Int) -> Int = addTwoInts
func printMathResult(_ mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) {
    print("Result: \(mathFunction(a, b))")
}
printMathResult(addTwoInts, 3, 5)
// 打印 "Result: 8"
func chooseStepFunction(backward: Bool) -> (Int) -> Int {
    return backward ? stepBackward : stepForward
}```

var currentValue = 3
let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)
// moveNearerToZero 现在指向 stepBackward() 函数。




# 闭包
* 闭包表达式语法(Closure Expression Syntax)

{ (parameters) -> returnType in
statements
}

reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in
return s1 > s2
})

reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in return s1 > s2 } )


* 根据上下文推断类型(Inferring Type From Context)

reversedNames = names.sorted(by: { s1, s2 in return s1 > s2 } )


* 单表达式闭包隐式返回(Implicit Returns From Single-Expression Closures)

reversedNames = names.sorted(by: { s1, s2 in s1 > s2 } )


* 参数名称缩写(Shorthand Argument Names)

reversedNames = names.sorted(by: { $0 > $1 } )


* 运算符方法(Operator Methods)

reversedNames = names.sorted(by: >)


* 尾随闭包(Trailing Closures)

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

reversedNames = names.sorted() { $0 > $1 }

reversedNames = names.sorted { $0 > $1 }

let strings = numbers.map {
(number) -> String in
var number = number
var output = ""
repeat {
output = digitNames[number % 10]! + output
number /= 10
} while number > 0
return output
}
// strings 常量被推断为字符串类型数组,即 [String]
// 其值为 ["OneSix", "FiveEight", "FiveOneZero"]


* 自动闭包(Autoclosures)

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"

上一篇下一篇

猜你喜欢

热点阅读