Document
Functions and Closures *******
Example Type |
Function |
Write Function as closure |
Call function |
Call function using trailing closure syntax |
() -> Void |
func sayHello() {
print("Hello")
}
|
let sayHello: ()->Void = {print("Hello")}
Or
let sayHello = {print("hello2")}
|
sayHello() |
N/A? |
(String) -> Void |
func sayHello(name: String) {
print("Hello \(name)")
}
|
let sayHello: (String) -> Void = { name in print("Hello, \(name)")}
Or
let sayHello = {(name:String) in print("Hello2, \(name)")}
|
sayHello(name:"Nick") |
N/A? |
Functions that use closures
*closures for parameters for functions
Example Type |
Function |
Write Function as closure |
Call function |
Call function using trailing closure syntax |
(String, ()->Void)
|
func sayHello(_ name:String, completion: ()->Void) {
print("Hi, \(name)")
completion()
}
|
write function as closure |
sayHello("nick", completion: {print("done.")})
|
sayHello("Nick") {
print("done)
}
|
(String, (String)->Void) |
func sayHello(_ name: String, completion: (String) -> Void) {
print("Hello \(name) ")
let reverseName = String(name.reversed())
completion(reverseName)
}
|
write function as closure |
sayHello("Nick", completion:{ reverse_name in
print(reverse_name)
print("done.")
})
|
sayHello("Nick") { reverse_name in
print(reverse_name)
}
|
Note:
You can call a function or call a function using trailing closure syntax. The former could be called the "long way" or "formal way" but there is not name for it, that is just calling a function.