【问题标题】:How can assing generic (associated type require) protocol as delegate to any controller?如何将泛型(关联类型要求)协议作为委托给任何控制器?
【发布时间】:2020-01-10 06:05:31
【问题描述】:

我有一个具有名为 MessageType 的关联类型的协议。

protocol MessageProtocol: class {
    associatedtype MessageType

    func sendMessage(_ with: MessageType)
}

然后在控制器中实现

extension MainController: MessageProtocol{

    typealias MessageType = String

    func sendMessage(_ with: MessageType) {
        // sending message
    }
}

我的目的是在其他控制器中使用协议作为委托,如下所示。

final class AnotherController {

    weak var messagerDelegate: MessageProtocol?

    ...
}

但我得到了那个错误

Protocol 'MessageProtocol' 只能用作通用约束 因为它有 Self 或关联的类型要求

有没有办法处理这个错误?

我正在阅读关于这种情况的 Big Nerd Ranch 博客文章。 https://www.bignerdranch.com/blog/why-associated-type-requirements-become-generic-constraints/

我了解了这种情况,但不知道如何实现?

谢谢,

【问题讨论】:

  • 没有灵丹妙药。我建议你阅读robnapier.net/start-with-a-protocol
  • @Alexander 谢谢,我正在阅读。
  • @ThanhVu 我阅读了问题和答案,但不知道如何申请自己。顺便可以标记为重复。
  • 嘿,@RobNapier,在 sendMessage 函数中只有 print 函数可以打印值。 AnotherController 调用委托,因为它使用 MessageProtocol 舒适的 MainController 类型生成。这太荒谬了,我知道。还有AnotherController 因为T.MessageType == String 而知道MessageType。我觉得simple和non-generic的功能一定更好。

标签: ios swift protocols


【解决方案1】:

我就是这样处理的。

final class AnotherController<T: MessageProtocol> where T.MessageType == String {

    weak var messagerDelegate: T?

    ...
}

如果我想以编程方式创建另一个Controller 实例,我就是这样创建的。

let instance = AnotherController<MainController>(frame: CGRect.zero)
instance.delegate = self
...

因为MainController 对来自MessageProtocol 的感觉很舒服

extension MainController: MessageProtocol{}

这可能并不常见,但对我有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-19
    • 1970-01-01
    • 2014-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多