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

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.

主站蜘蛛池模板: 顺平县| 敦化市| 离岛区| 仲巴县| 荆门市| 海林市| 靖宇县| 嘉黎县| 五华县| 二连浩特市| 黄龙县| 增城市| 辉南县| 韩城市| 通河县| 张家川| 临清市| 洛阳市| 特克斯县| 祁东县| 乌兰县| 四平市| 苏尼特左旗| 丹江口市| 镇巴县| 丽江市| 麟游县| 土默特右旗| 筠连县| 达尔| 锡林浩特市| 禄丰县| 车致| 池州市| 乐山市| 洛扎县| 温泉县| 陇西县| 方山县| 科技| 白城市|