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

Generic types

You can also make complex types generic. In our example, we created this wrapper around a list of Runnable, called ManyRunner. The job of a many runner is to run all of the runnables. The ManyRunner is itself Runnable, so we have created a kind of type recursion, as follows:

struct ManyRunner<T>: Runnable where T: Runnable {
let runnables: [T]
func run() {
runnables.forEach { $0.run() }
}
}

Let's also provide a base object that runs a simple Incrementer. Each time the Incrementer is run, the static count will increment, to keep track of the number of invocations:

struct Incrementer: Runnable {
private(set) static var count = 0
func run() {
Incrementer.count += 1
}
}

When using generics on types, remember that the types have to be the same:

// This works
let runner = ManyRunner(runnables: [Incrementer(),Incrementer()])
runner.run()
assert(Incrementer.count == 2)
// runner is of type ManyRunner<Incrementer>



ManyRunner(runnables: [Incrementer(), Runners(runnables: [Incrementer()])] as [Runnable]).run()
// This produces the following compile error
// In argument type '[Runnable]', 'Runnable' does not conform to expected type 'Runnable'

We'll look at how to overcome these limitations in Chapter 8Swift-Oriented Patterns.

主站蜘蛛池模板: 斗六市| 大港区| 贡觉县| 林口县| 北京市| 定边县| 滨州市| 阜新市| 石泉县| 利辛县| 阜宁县| 霍林郭勒市| 甘泉县| 衢州市| 博乐市| 阳谷县| 镇沅| 什邡市| 木兰县| 获嘉县| 泸西县| 扎兰屯市| 隆安县| 华亭县| 临澧县| 延安市| 福海县| 千阳县| 武夷山市| 迭部县| 曲松县| 白城市| 静安区| 杭锦旗| 孙吴县| 江都市| 建德市| 扎兰屯市| 科技| 申扎县| 通渭县|