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

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
主站蜘蛛池模板: 宜兰市| 汉源县| 达尔| 新晃| 大名县| 泊头市| 安溪县| 涟水县| 普安县| 浏阳市| 公安县| 锡林浩特市| 都昌县| 敖汉旗| 罗甸县| 许昌市| 陵川县| 安乡县| 宽甸| 巩义市| 娱乐| 宾川县| 正镶白旗| 晋江市| 泸水县| 普洱| 洮南市| 绿春县| 峨山| 榆树市| 永兴县| 庐江县| 开平市| 类乌齐县| 鄂尔多斯市| 利辛县| 林甸县| 灵璧县| 静安区| 法库县| 吕梁市|