oge 封包工具 封包
什么是封包? (What is Closure?)
Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.
闭包是独立的功能块,可以在代码中传递和使用。 Swift中的闭包类似于C和Objective-C中的块以及其他编程语言中的lambda。
Closure is a function and “func” keyword
闭包是函数和“ func ”关键字
- Closure is a block of code that you can assign to a variable. 闭包是可以分配给变量的代码块。
In Swift Variables “var” and Constants “let” store information, Functions “func” execute tasks and Closures have a function code in form of a variable and can be passed around.
在Swift变量“ var ”和常量“ let ”中存储信息,函数“ func ”执行任务,闭包具有变量形式的函数代码,并且可以传递。
封闭的类型有哪些? (What are the types of the Closure?)
- Closure without niether parameters nor return value. 不带任何参数或返回值的闭包。
- Closure that accepts parameters. 接受参数的闭包。
- Closure returns value. 闭包返回值。
- Trailing Closure 尾随闭包
没有参数或返回值的闭包 (Closure without parameters or return value)
var myClosure = {
print("Hello I'm a Closure")
}myClosure() => Hello I'm a Closure
接受参数的闭包 (Closure that acceptes parameters)
var closure: (String) -> Void = { str in
print(str)
}var closure: (Int, Int) -> Void = { first, second in
print(first + second)
}
Since closures parameters don’t have names you can refer to them with $ + parameters number
由于闭包参数没有名称,因此可以使用$ +参数编号引用它们
var closure: (Int, Int) -> Void = {
print($0 + $1)
}closure(3, 2) => 5
闭包返回值 (Closure that returns values)
var closure: () -> String = {
return "Hello Closure"
}var value = closure()print(value) => Hello Closure
closures can also accept parameters and return value
闭包也可以接受参数和返回值
var addTwoNumbers: (Int, Int) -> Int = {
return $0 + $1
}
addTwoNumbers(4, 5) => 9
尾随闭包 (Trailing Closure)
If the last parameter to a function is closure that’s called trailing closure
如果函数的最后一个参数是闭包,则称为尾随闭包
func callMe(closure: () -> Void) {
print("will call you")
closure()
print("did call you")
}callMe {
print("calling you...")
}=> will call you
=> calling you...
=> did call you
Another example of the trailing closure with parameter
带参数的尾随闭包的另一个示例
func callMe(name: String, closure: (String) -> Void) {
print("\(name) will call you")
closure(name)
print("\(name) did call you")
}callMe(name: "Smith") { name in
print(name, "is calling you")
}=> Smith will call you
=> Smith is calling you
=> Smith did call you
Trailing closure with parameter and returns value
带参数的尾随闭包并返回值
func callMe(name: String, closure: (String) -> String) -> String {
return closure(name)
}var whoIsCalling = callMe(name: "Smith") { (name) -> String in
return name
}print(whoIsCalling)=> Smith is calling.
oge 封包工具 封包