- Hands-On Design Patterns with Swift
- Florent Vilmart Giordano Scalzo Sergio De Simone
- 193字
- 2021-07-02 14:45:02
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 8, Swift-Oriented Patterns.
推薦閱讀
- Python絕技:運(yùn)用Python成為頂級數(shù)據(jù)工程師
- 數(shù)據(jù)挖掘原理與實(shí)踐
- 計(jì)算機(jī)信息技術(shù)基礎(chǔ)實(shí)驗(yàn)與習(xí)題
- Oracle RAC 11g實(shí)戰(zhàn)指南
- 云計(jì)算服務(wù)保障體系
- Hadoop與大數(shù)據(jù)挖掘(第2版)
- 數(shù)據(jù)化網(wǎng)站運(yùn)營深度剖析
- Enterprise Integration with WSO2 ESB
- 數(shù)據(jù)庫原理與設(shè)計(jì)(第2版)
- SQL Server深入詳解
- 改進(jìn)的群智能算法及其應(yīng)用
- 區(qū)塊鏈應(yīng)用開發(fā)指南:業(yè)務(wù)場景剖析與實(shí)戰(zhàn)
- 一本書讀懂區(qū)塊鏈(第2版)
- 數(shù)據(jù)庫高效優(yōu)化:架構(gòu)、規(guī)范與SQL技巧
- 大數(shù)據(jù):從海量到精準(zhǔn)