Created
October 23, 2020 13:07
-
-
Save fredriccliver/9233c9cfa79b2c23b2dafabd133b8df9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Without params and return type | |
let closureFunc = { | |
print("Printed from a closure") | |
} | |
closureFunc() // Printed from a closure | |
// With a parameter | |
let closureWithParams = { (name:String) in | |
print("My name is \(name)") | |
} | |
closureWithParams("John") // My name is John | |
// With a return | |
let closureWithReturn = { () -> String in | |
return "Hi mate" | |
} | |
print(closureWithReturn()) // Hi mate | |
// To use closure as a parameter | |
let imJohn = { () -> String in | |
return "John" | |
} | |
let printName = { (getName: () -> String) in | |
print("I am \(getName())") | |
} | |
printName(imJohn) // I am John | |
// To use two parameters in a closure | |
let manify = { | |
return "a man" | |
} | |
let genderify = { (_ name:String, gender: () -> String ) in | |
print("\(name) is \(gender())") | |
} | |
genderify("John", manify) // John is a man | |
// Using a trailing clousre in a different syntax | |
genderify("Sansa", { | |
return "a women" | |
}) // Sansa is a women | |
// Complex case | |
let detailify = { (adj: ()-> String) in | |
genderify("John", { | |
return "\(manify()) and \(adj())" | |
}) | |
} | |
detailify({ | |
return "short" | |
}) // John is a man and short | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment