Swift: Pass a closure to function
By somaria
2022-12-28
import Cocoa /* Create a simple closure */ let sayHello = { print("Hello, World!") } /* Call the closure */ sayHello() /* Create a function that can take a closure as a parameter */ func sayHelloTo(name: String, withGreeting greeting: () -> ()) { print("Hello, \(name)!") greeting() } /* Call the function, passing in the closure */ sayHelloTo(name: "John", withGreeting: sayHello)

Output

Hello, World!

Hello, John!

Hello, World!