官术网_书友最值得收藏!

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
主站蜘蛛池模板: 霍邱县| 赤城县| 万州区| 焦作市| 依兰县| 泾阳县| 巴中市| 南丰县| 丰镇市| 营山县| 颍上县| 星座| 海丰县| 通榆县| 临澧县| 乐亭县| 上栗县| 玉林市| 双江| 都昌县| 崇阳县| 麻阳| 清苑县| 资溪县| 昌邑市| 汶川县| 青浦区| 舞阳县| 抚州市| 清水河县| 高雄市| 广宗县| 精河县| 梁河县| 咸丰县| 丹棱县| 梁山县| 樟树市| 石家庄市| 西吉县| 浪卡子县|