Created
April 22, 2018 16:35
-
-
Save Moximillian/34b3378566344f6f5e1fd31da269e93d to your computer and use it in GitHub Desktop.
Examples how to use closures
This file contains 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
/* regular closure */ | |
/// definition of function with closure parameter | |
func test(closure: (Int) -> String) { | |
let result = closure(42) | |
print("Result is \(result)") | |
} | |
// using the function | |
test { i in | |
return "\(i + 20)" | |
} | |
// above outputs "result is 62" | |
/// definition of function with closure parameter, the closure does not have arguments, only return value | |
func navigateTo<T: UIViewController>(controller: @escaping () -> T) { | |
let target = controller() | |
print("target is \(target)") | |
} | |
// using the function | |
navigateTo { | |
let vc = UIViewController() | |
return vc | |
} | |
// above outputs "target is <UIViewController: 0x...>" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment