You can call this like
func doImportantWork(first: () -> Void, second: String) {
print("About to start first work")
first()
print("About to start second work")
print("\(second) work done!")
}
func printFirst() {
print("First work done!")
}
doImportantWork(first: printFirst, second: "Second")
However to get a trailing closure
you need to change the first
so that it trailing
func doImportantWork(second: String, first: () -> Void) {
print("About to start first work")
first()
print("About to start second work")
print("\(second) work done!")
}
doImportantWork(second: "Second") {
print("First work done!")
}
You can even have multiples trailing closures
func doImportantWork(first: () -> Void, second: (String) -> Void) {
print("About to start first work")
first()
print("About to start second work")
second("Second")
}
doImportantWork {
print("First work done!")
} second: { string in
print("\(string) work done!")
}
or even more
func doImportantWork(first: () -> Void, second: (String) -> Void, third: (Int, String) -> Void) {
print("About to start first work")
first()
print("About to start second work")
second("Second")
print("About to start third work")
third(3, "Third")
}
doImportantWork {
print("First work done!")
} second: { string in
print("\(string) work done!")
} third: { number, string in
print("\(number). \(string) work done!")
}