- Swift 4 Programming Cookbook
- Keith Moon
- 371字
- 2021-07-08 10:21:30
There's more...
Protocol conformance can be applied to classes, structs, enums, and even other protocols, allowing an instance to be stored and passed without needing to know how it's implemented under the hood. This provides many benefits, including testing using mock objects and changing implementations without changing how and where the implementations are used.
Let's add a feature to our app that lets us set a reminder for a contact's birthday, which we will also want to save to our remote database.
We can use class inheritance to give our reminder the save functionality, but a reminder should not have the same features and functionality as a person, and our process for saving a reminder may be different to that used for a person.
Instead, we can create our Reminder object and have it conform to the Saveable protocol:
class Reminder: Saveable {
var dateOfReminder: String // There is a better to store dates, but this suffice currently.
var reminderDetail: String // eg. Alissa's birthday
init(date: String, detail: String) {
dateOfReminder = date
reminderDetail = detail
}
var saveHandler: ((Bool) -> Void)?
var saveNeeded: Bool = true
func saveToRemoteDatabase(handler: @escaping (Bool) -> Void) {
saveHandler = handler
// Send reminder information to remove database
// Once remote save is complete, it calls saveComplete(success: Bool)
}
func saveComplete(success: Bool) {
saveHandler?(success)
}
}
Our Reminder object conforms to Saveable and implements all the requirements.
We now have two objects that represent very different things and have different functionalities, but they both implement Saveable, and therefore we can treat them in a common way.
To see this in action, let's create an object that will manage the saving of information in our app:
class SaveManager {
func save(_ thingToSave: Saveable) {
thingToSave.saveToRemoteDatabase { success in
print("Saved! Success: \(success))")
}
}
}
let colin = createPerson("Colin", "Alfred", "Moon") // This closure was covered in the previous recipe
let birthdayReminder = Reminder(date: "27/11/1982", detail: "Colin's Birthday")
let saveManager = SaveManager()
saveManager.save(colin)
saveManager.save(birthdayReminder)
In the preceding example, our SaveManager doesn't know the underlying types that it is being passed, but it doesn't need to. It receives instances that conform to the Saveable protocol, and can, therefore, use the interface provided by Saveable to save each object.
- Extending Jenkins
- Learning Cython Programming
- Python自然語言處理實戰(zhàn):核心技術與算法
- 自制編譯器
- Ext JS Data-driven Application Design
- Learning SAP Analytics Cloud
- VSTO開發(fā)入門教程
- Neo4j Essentials
- Full-Stack Vue.js 2 and Laravel 5
- Python Web數(shù)據(jù)分析可視化:基于Django框架的開發(fā)實戰(zhàn)
- R語言與網(wǎng)絡輿情處理
- C語言程序設計實驗指導 (第2版)
- Unity 2018 Shaders and Effects Cookbook
- Odoo 10 Implementation Cookbook
- uni-app跨平臺開發(fā)與應用從入門到實踐