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

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
主站蜘蛛池模板: 镇坪县| 襄汾县| 常州市| 大化| 阿拉善右旗| 长白| 宾川县| 大港区| 邓州市| 确山县| 巨野县| 海丰县| 定边县| 叙永县| 神农架林区| 工布江达县| 莎车县| 白河县| 焦作市| 静乐县| 抚宁县| 正宁县| 西宁市| 奎屯市| 进贤县| 延庆县| 德阳市| 太仆寺旗| 宁陕县| 肇州县| 涞源县| 湖北省| 星座| 淅川县| 青神县| 淮安市| 澄迈县| 临沂市| 罗平县| 铜川市| 南木林县|