- 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
推薦閱讀
- Learning JavaScriptMVC
- 文本挖掘:基于R語言的整潔工具
- R數(shù)據(jù)科學(xué)實戰(zhàn):工具詳解與案例分析(鮮讀版)
- 區(qū)塊鏈通俗讀本
- Hands-On Mathematics for Deep Learning
- 數(shù)據(jù)科學(xué)工程實踐:用戶行為分析與建模、A/B實驗、SQLFlow
- 圖數(shù)據(jù)實戰(zhàn):用圖思維和圖技術(shù)解決復(fù)雜問題
- 云原生數(shù)據(jù)中臺:架構(gòu)、方法論與實踐
- Spark分布式處理實戰(zhàn)
- MySQL DBA修煉之道
- 企業(yè)主數(shù)據(jù)管理實務(wù)
- MySQL技術(shù)內(nèi)幕:InnoDB存儲引擎
- Rust High Performance
- 數(shù)據(jù)庫原理及應(yīng)用:SQL Server 2016
- Arquillian Testing Guide