swift - 符合具有通用约束的协议(protocol)的弱属性

标签 swift generics protocols

我编写了我遇到问题的类似实现的简化版本。任何人都知道为什么会这样,最终如何解决?

注意:代码只是示例,以使其尽可能简单

protocol Alertable {
   associatedtype Alert

   func show(alertOfType alertType: Alert)
}
protocol ViewControllerDelegate: class, Alertable {
}

final class MyViewController: UIViewController {

   // MARK: - Types

   enum AlertType {
      case alert
      case warning
   }
}

extension MyViewController: ViewControllerDelegate {
   typealias Alert = AlertType   // ! here i specify the associated type !

   func show(alertOfType alertType: Alert) {
      // code..
   }
}

到目前为止一切顺利。但是,这里我得到错误:

final class ViewModel {

   // ERROR: Protocol 'ViewControllerDelegate' can only be used as a generic constraint because it has Self or associated type requirements.
   weak var viewController: ViewControllerDelegate?

   init(viewController: ViewControllerDelegate?) {
      self.viewController = viewController
   }

   private func someFunction() {

      // ERROR: Member 'show' cannot be used on value of protocol type 'NewsFeedViewControllerInput'; use a generic constraint instead.
      viewController?.show(alertOfType: .warning)

      // code..
   }
}

谢谢

最佳答案

你有点误会了。当你定义:

protocol ViewControllerDelegate: class, Alertable {}

extension MyViewController: ViewControllerDelegate {
    typealias Alert = AlertType   // ! here i specify the associated type !

    func show(alertOfType alertType: Alert) {
        // code..
    }
}

类型别名在 MyViewController 中定义,但在 ViewControllerDelegate 中没有定义。目前尚不清楚为什么您在这个问题中需要 ViewControllerDelegate,但也许有些东西我们在真实应用中看不到。

ViewModel 中,将 ViewControllerDelegate 更改为 MyViewController:

final class ViewModel {
    weak var viewController: MyViewController?
    // ...
}

还有一件事,尽管与错误无关:您使用了许多 final class。它们应该是 struct 吗?

关于swift - 符合具有通用约束的协议(protocol)的弱属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54385370/

相关文章:

swift - CoreData 使用 iCloud,不使用同步通知

ios - 如何在集合类型约束中制作泛型?

c# - 使用泛型方法将继承的泛型类添加到字典

c - Wireshark - 以编程方式修改 pcap 文件中的数据包

ios - 协议(protocol)类型不能符合协议(protocol),因为只有具体类型才能符合协议(protocol)

ios - 如何在 Swift 的 textView 中突出显示文本?

swift - iOS实时检测相机的一些标记

swift - requestAccessForMediaType 不请求许可

java - 当使用 Bounded 类型参数或直接类型接口(interface)时

ios - 如何在 swift 中使用委托(delegate)和协议(protocol)编辑和传回单元格数据