- 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.
推薦閱讀
- 復雜性思考:復雜性科學和計算模型(原書第2版)
- Voice Application Development for Android
- Hands-On Mathematics for Deep Learning
- 金融商業算法建模:基于Python和SAS
- MySQL技術內幕:InnoDB存儲引擎
- 企業大數據處理:Spark、Druid、Flume與Kafka應用實踐
- Google Cloud Platform for Architects
- 數據中臺實戰:手把手教你搭建數據中臺
- 領域驅動設計精粹
- 掌中寶:電腦綜合應用技巧
- Python金融數據挖掘與分析實戰
- Learn Selenium
- GameMaker Game Programming with GML
- Managing Software Requirements the Agile Way
- Access 2013 數據庫管理與應用從新手到高手