Skip to content

Instantly share code, notes, and snippets.

@novinfard
Last active June 24, 2018 11:25
Show Gist options
  • Save novinfard/a6deee30bc4a291f575cdaf73ab2ce99 to your computer and use it in GitHub Desktop.
Save novinfard/a6deee30bc4a291f575cdaf73ab2ce99 to your computer and use it in GitHub Desktop.
[Closures in Swift]
//** simple form
// simple
let clos1 = { () -> Void in
print("Hello World!")
}
clos1()
// simple 2
let clos2 = { (name: String) -> Void in
print("Hello \(name)!")
}
clos2("Soheil")
func testClosure(handler: (String) -> Void) {
handler("John")
}
testClosure(handler: clos2)
// simple 3
let clos3 = { (name: String) -> String in
return "Hello \(name)!"
}
var message = clos3("Ahmad")
print(message)
//** shorthand syntax
func testFunction(num: Int, handler:()->Void) {
for _ in 0 ..< num {
handler()
}
}
let clos = {
() -> Void in
print("Hello From Standard Syntax")
}
testFunction(num: 5, handler: clos)
// OR
testFunction(num: 5, handler: {print("Hello From Shorthand Closure")})
// OR
testFunction(num: 5) {
print("Hello From Shorthand Closure")
}
//** with input parameter
func testFunction2(num: Int, handler:(_ : String, _: String)->Void) {
for _ in 0..<num {
handler("Me", "Student")
}
}
testFunction2(num: 5) {
print("Hello by \($0) as \($1)")
}
// OR
testFunction2(num: 5) { (name, job) in
print("Hello by \(name) as \(job)")
}
// OR
testFunction2(num: 5) { name, job in
print("Hello by \(name) as \(job)")
}
// another shorthand syntax
let clos5a = { (firstName: String, familyName: String) -> Void in
print("\(firstName) \(familyName)")
}
// OR
let clos5b: (String, String) ->Void = {
print("\($0) \($1)")
}
// OR
let clos5: (String, String) -> () = {
print("\($0) \($1)")
}
clos5("Steve","Jobs")
// ** delete return keyword in one line statement
let clos6a = { (first: Int, second: Int) -> Int in
return first + second
}
// OR
let clos6 = { (first: Int, second: Int) -> Int in
first + second
}
clos6(10, 15)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment