我遇到了这个我无法解决的问题,也没有找到太多相关信息。
我的情况是,我想从工厂函数返回一个 UIViewController
实例,它也实现了一个协议(protocol),我们称它为 Protocol
。我想知道是否有人遇到过这种情况并找到了任何解决方案?
在 Objective-C 中它看起来像这样:
- (UIViewController<Protocol>*)createControllerForIdentifier:(NSString*)identifier
有什么 Swift 的写法吗?
将 Protocol
限制为具体类或子类对我来说是可以的。
我找到了 this thread但无法转换为我的情况
感谢您的帮助。
最佳答案
根据具体情况,有多种选择。这是一种可能有所帮助的通用方法。但是,我建议重写代码,这样这就不是真正的问题。 Swift 和 Objective-C 是不同的语言,一些设计模式根本无法(而且可能永远不会)适用于这两种语言。在这种情况下,移植代码需要从头开始重新考虑代码。
您可以通过如下引入绑定(bind)协议(protocol)来实现安全性和便利性:
// protocol you want to implement
// this may possibly be implemented by other types besides our Base (no restrictions)
protocol P1 {
func run()
}
// base class of objects to instantiate
class Base {
// Base specific method
func display() {
print("Displaying...")
}
}
// wrapper to get both P1 and Base
// our special protocol will be dedicated to P1 and Base
protocol PB : P1 { // already a P1
// property to safely get this instance as a Base without casting
var asBase : Base { get }
}
// extension to safely implement the binding for P1 and Base
// anything we implement in this extension is safe for both P1 and Base
extension PB where Self : Base {
var asBase : Base { return self }
}
// concrete subclass of Base which also implements PB and hence P1
class X : Base, PB {
// implement protocol
func run() {
print("Running...")
}
}
// factory function to make a concrete instance of Base implementing P1
func makePB() -> PB {
return X()
}
let pb = makePB()
pb.run() // directly access as P1
pb.asBase.display() // both safe and easy to access as Base
关于ios - 返回实现协议(protocol)的具体类的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35206507/