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

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.

主站蜘蛛池模板: 临猗县| 方城县| 安国市| 河津市| 百色市| 玉林市| 奇台县| 乌审旗| 宣汉县| 牟定县| 博湖县| 彩票| 梁山县| 泸溪县| 清远市| 富民县| 屏边| 灵丘县| 于田县| 乡城县| 沈阳市| 乌拉特后旗| 信丰县| 桃园县| 碌曲县| 九龙坡区| 尉氏县| 滦南县| 特克斯县| 田东县| 逊克县| 西乌珠穆沁旗| 大洼县| 龙山县| 沙雅县| 两当县| 锦州市| 洞口县| 闻喜县| 台前县| 当阳市|