- 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數(shù)據(jù)挖掘:入門(mén)、進(jìn)階與實(shí)用案例分析
- 數(shù)據(jù)之巔:數(shù)據(jù)的本質(zhì)與未來(lái)
- Game Development with Swift
- Effective Amazon Machine Learning
- Oracle RAC 11g實(shí)戰(zhàn)指南
- 區(qū)塊鏈:看得見(jiàn)的信任
- Oracle高性能自動(dòng)化運(yùn)維
- SQL優(yōu)化最佳實(shí)踐:構(gòu)建高效率Oracle數(shù)據(jù)庫(kù)的方法與技巧
- Lego Mindstorms EV3 Essentials
- 云數(shù)據(jù)中心網(wǎng)絡(luò)與SDN:技術(shù)架構(gòu)與實(shí)現(xiàn)
- 編寫(xiě)有效用例
- Instant Autodesk AutoCAD 2014 Customization with .NET
- 大數(shù)據(jù)技術(shù)原理與應(yīng)用:概念、存儲(chǔ)、處理、分析與應(yīng)用
- 菜鳥(niǎo)學(xué)SPSS數(shù)據(jù)分析
- 數(shù)據(jù)賦能