Skip to content

Instantly share code, notes, and snippets.

@Moximillian
Created April 22, 2018 16:35
Show Gist options
  • Save Moximillian/34b3378566344f6f5e1fd31da269e93d to your computer and use it in GitHub Desktop.
Save Moximillian/34b3378566344f6f5e1fd31da269e93d to your computer and use it in GitHub Desktop.
Examples how to use closures
/* 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