ios - 返回实现协议(protocol)的具体类的对象

标签 ios swift

我遇到了这个我无法解决的问题,也没有找到太多相关信息。

我的情况是,我想从工厂函数返回一个 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/

相关文章:

ios - 尝试使用 Swift3 将图像上传到 CloudKit 时出错

iOS Swift 2.0 - AvAudioPlayer 没有播放任何声音

swift - NSLocale.preferredLanguages 在更改 NSUserDefaults 时不会更改

iphone - 如何使除选定一个以外的所有表格 View 单元格变灰

ios - 每次重新启动 Xcode 8 后, Storyboard 中仅针对一个 ViewController 重复警告

ios - 当我使用数组时 Xcode 8 永远索引

ios - 如何禁用默认的删除滑动操作并改为显示我的自定义滑动操作?

ios - 使用 Swift 遍历 Firebase 中的嵌套快照子项

ios - 如何使用 carto-mobile SDK 验证 map 位置是否在 map 边界内

ios - 完全删除 View Controller - Swift