- Hands-On Design Patterns with Swift
- Florent Vilmart Giordano Scalzo Sergio De Simone
- 187字
- 2021-07-02 14:45:02
Generics, protocols, and associated types
You can also use associated types in your protocols. These associated types let you define protocols that are generics, like this: RunnableWithResult. We can implement a bunch of logic and code around the run() method, without actually knowing anything about the return types. We'll encounter this construction many times in this book, so it's important that you're comfortable with associate types:
protocol RunnableWithResult {
associatedtype ResultType
func run() -> ResultType
}
struct RunnersWithResult<T>: RunnableWithResult where T: RunnableWithResult {
let runnables: [T]
func run() -> [T.ResultType] {
return runnables.map { $0.run() }
}
}
Like with generic types, you can't mix and match heterogeneous types. The following example will not compile; later in this book, you'll see strategies for overcoming this common problem when dealing with generics:
struct IntRunnable {
func run() -> Int {
return 0
}
}
struct StringRunnable {
func run() -> String {
return "OK"
}
}
let runnables: [RunnableWithResult] = [StringRunnable(), IntRunnable()]
This will yield the following dreaded error:
Protocol 'RunnableWithResult' can only be used as a generic constraint because it has Self or associated type requirements
推薦閱讀
- 計算機組成原理與接口技術:基于MIPS架構實驗教程(第2版)
- MySQL數據庫進階實戰
- Python金融大數據分析(第2版)
- Architects of Intelligence
- 大數據:規劃、實施、運維
- 數據庫系統原理及應用教程(第4版)
- 算法與數據中臺:基于Google、Facebook與微博實踐
- 計算機應用基礎教程上機指導與習題集(微課版)
- Hands-On System Programming with C++
- 企業級大數據項目實戰:用戶搜索行為分析系統從0到1
- Arquillian Testing Guide
- 深入理解Flink:實時大數據處理實踐
- Learn Selenium
- Kafka權威指南(第2版)
- Applying Math with Python