我正在嘗試編寫一個通用中介基類(Mediator),它將對等類註冊到實例化中定義的特定協議(在對等類擴展上)。你如何使用多個類型參數 - Swift 2?
調解員和同伴的子類不應該彼此瞭解。當所有人聯繫起來時,他們的關係就被定義了這是爲了使每個組件都是模塊化的。
如果我只使用一種類型的參數,例如:
class Mediator<T, U> {
private var peers = [T]()
func registerPeer(peer: T) {
self.peers.append(peer)
}
}
然後一個對等體正確地登記。
我希望T或U都能夠被附加到同位體[]上。
我找的,只有改變Mediator的同行[]和registerPeer()允許混合或T或U
// Mediator
class Mediator<T, U> {
// I want this to be an Array that can be T OR U
private var peers = Array<T|U>()
// I want peer: to be either T OR U
func registerPeer(peer: <T|U>) {
self.peers.append(peer)
}
}
class RootModuleMediator<T, U> : Mediator<T, U> {}
protocol RootModuleMediatorsIOInterface { func someFunction() }
extension RootModuleMediator : RootModuleMediatorsIOInterface { func someFunction() { print("RootModuleMediator someFunction() printed")}}
protocol RootModuleMediatorsViewInterface { func aFunction() }
extension RootModuleMediator : RootModuleMediatorsViewInterface { func aFunction() { print("RootModuleMediator aFunction() printed")}}
// Peer
class Peer<T> {
private var mediator : T?
func registerMediator(mediator: T) { self.mediator = mediator }
}
// View Peer
class RootModuleView<T> : Peer<T> {}
protocol RootModuleViewsMediatorInterface { func someFunction() }
extension RootModuleView : RootModuleViewsMediatorInterface { func someFunction() { print("RootModuleView someFunction() printed") }}
// IO Peer
class RootModuleIO<T> : Peer<T> {}
protocol RootModuleIOsMediatorInterface { func someFunction() }
extension RootModuleIO : RootModuleIOsMediatorInterface { func someFunction() { print("RootModuleIO someFunction() printed") }}
// Wiring components together
let rootModuleIO = RootModuleIO<RootModuleMediatorsIOInterface>()
let rootModuleView = RootModuleView<RootModuleMediatorsViewInterface>()
let rootModuleMediator = RootModuleMediator<RootModuleIOsMediatorInterface, RootModuleViewsMediatorInterface>()
rootModuleIO.registerMediator(rootModuleMediator)
rootModuleView.registerMediator(rootModuleMediator)
rootModuleMediator.registerPeer(rootModuleIO)
rootModuleMediator.registerPeer(rootModuleView)
// I want the following function to print "RootModuleIO someFunction() printed"
rootModuleMediator.peers[0].someFunction()
謝謝,不是我在尋找解決方案。因爲我希望Mediator對RootModuleMediatorsIOInterface或RootModuleMediatorsViewInterface沒有直接的瞭解。我更新了我的問題並添加了更多詳細信息。 –