- Swift 4 Programming Cookbook
- Keith Moon
- 484字
- 2021-07-08 10:21:29
There's more...
We've seen how we can store closures, but we can also use them as method parameters. This pattern can be really useful when we want to be notified when a long-running task is completed.
Let's imagine that we want to save the details of our person object to a remote database, maybe for backup or use on other devices. We'll amend our Person class to include this save functionality, and in the process, see how we can pass in a closure, store it, and execute it at a later time.
Add the following code to our Person class:
class Person {
//....
var saveHandler: ((Bool) -> Void)?
func saveToRemoteDatabase(handler: @escaping (Bool) -> Void) {
saveHandler = handler
// Send person information to remove database
// Once remote save is complete, it calls saveComplete(Bool)
}
func saveComplete(success: Bool) {
saveHandler?(success)
}
}
We define an optional variable to hold onto the save handler during the long-running save operation. Our closure will take a Bool to indicate whether the save was a success:
var saveHandler: ((Bool) -> Void)?
Let's define a method to save our Person object, which takes a closure as a parameter:
func saveToRemoteDatabase(handler: @escaping (Bool) -> Void) {
saveHandler = handler
// Send person information to remove database
// Once remote save is complete, it calls saveComplete(Bool)
}
Our function stores the given closure in the variable, and then starts the process to save to the remote database (the actual implementation of this is outside the scope of this recipe). This save process will call the saveComplete method when completed. We added a modifier, @escaping, just before the closure type definition. This tells the compiler that, rather than using the closure within this method, we intend to store the closure and use it later. The closure will be escaping the scope of this method. This modifier is needed to prevent the compiler from doing certain optimizations that would be possible if the closure was nonescaping.
With the save operation complete, we can execute the saveHandler variable, passing in the success boolean. However, since we stored the closure as optional, we need to unwrap it by adding a ? after the variable name. If saveHandler has a value, the closure will be executed; if it is nil, the expression is ignored:
func saveComplete(success: Bool) {
saveHandler?(success)
}
Now that we have a function that takes a closure, let's see how we call it:
let dave = createPerson("David", "Ernest", "Moon")
dave.saveToRemoteDatabase(handler: { success in
print("Saved finished. Successful: \(success))")
})
Swift provides a more concise way to provide closures to functions. When a closure is the last (or only) parameter, Swift allows it to be provided as a trailing closure--that is, the parameter name can be dropped and the closure can be specified after the parameter brackets. So we can, instead, do the following:
dave.saveToRemoteDatabase { success in
print("Saved finished. Successful: \(success))")
}
- Mastering Spring MVC 4
- TestNG Beginner's Guide
- 軟件測試項目實戰之性能測試篇
- Instant QlikView 11 Application Development
- Java EE 7 Development with NetBeans 8
- Quarkus實踐指南:構建新一代的Kubernetes原生Java微服務
- Spring實戰(第5版)
- 程序員修煉之道:通向務實的最高境界(第2版)
- C語言程序設計學習指導與習題解答
- 大模型RAG實戰:RAG原理、應用與系統構建
- C語言程序設計同步訓練與上機指導(第三版)
- Mastering JavaScript High Performance
- Windows Phone 7.5:Building Location-aware Applications
- SQL Server數據庫管理與開發兵書
- Mobile Device Exploitation Cookbook