swift 学习笔记二:Closures

前端之家收集整理的这篇文章主要介绍了swift 学习笔记二:Closures前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Closure Expression Syntax(语法定义)

{ ( parameters) -> return type in
statements
}

看一个例子,对字符串数组排序:

var names = […]
var reversed = sorted(names,{(s1: String,s2: String) -> Bool in
return s1 > s2
})

swift还提供了一连串的简化方法
1. Referring Type from Context (从上下文环境中推断参数和返回值的类型,就可以省略不写了)

var reversed = sorted(names,{s1,s2 in return s1 > s2})


2. Implicit Returns from Single-Expression Closures(如果只有一行语句,return 也可以省略)

var reversed = sorted(names,s2 in s1 > s2})


3. Shorthand Argument Names (命名参数也可以省略,用 $n 代替)

var reversed = sorted(names,{$0 > $1})

4. Operator Functions (直接用操作符)

var reversed = sorted(names,>)


. Trailing Closures (如果Closure是最后一个参数,可以写在参数括号的外面)

sample 1:
var reversed = sorted(names) { $0 > $1}

sample 2:
let digitNames = [
0 : "Zero" , 1 : "One" ,216)">2 : "Two" ,216)">3 : "Three" ,216)">4 : "Four" ,
5 : "Five" ,216)">6 : "Six" ,216)">7 : "Seven" ,216)">8 : "Eight" ,216)">9 : "Nine"
]
let numbers = [ 16 ,216)">58 ,216)">510 ]

numbers . map {
(
var number) -> String in
var output = ""
while number > 0 {
output =
digitNames [number% 10 ]! + output
number /=
10
}
return output
}

. Capturing Values (访问上下文中的变量,即使外部函数已经结束,它所捕获的变量依然存在,见下面例子中的runningTotal )

func makeIncrementer(forIncrement amount: Int ) -> () -> Int {

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

return incrementer
}

let incrementByTen = makeIncrementer (forIncrement: 10 )
incrementByTen ()10
incrementByTen ()20

let incrementBySeven = @H_678_404@7 )
incrementBySeven ()7
incrementBySeven ()14

. Closures Are Reference Types (Closure是引用类型,还是看 runningTotal)

let alsoIncrementByTen = incrementByTen
alsoIncrementByTen() 30
原文链接:https://www.f2er.com/swift/326268.html

猜你在找的Swift相关文章