我可以使用通用协议以非通用类型描述委托吗?

问题描述

我试图用通用协议描述一个委托属性,而不使该类通用:

protocol ActionHandler: class {
  associatedtype Action
  func handle(_ action: Action)
}

enum SomeAction {
  case dismiss
}

class Foo {
  typealias Action = SomeAction
  // ? Protocol 'ActionHandler' can only be used as a generic constraint because it has Self or associated type requirements
  weak var handler: ActionHandler?
  // Ideally some form of ActionHandler<Action>?
}

class Handler: ActionHandler {
  func handle(_ action: SomeAction) {
    switch action {
      case .dismiss:
        print("dismiss")
    }
  }
}

let handler = Handler()
Foo().handler = handler

我可以改为用闭包代替该属性,但是我不太喜欢这种模式,因此对于协议中描述的每种方法,我都必须这样做。

enum SomeAction {
  case dismiss
}

class Foo {
  typealias Action = SomeAction
  var handleAction: ((Action) -> Void)?
}

class Handler {
  func handle(_ action: SomeAction) {
    switch action {
      case .dismiss:
        print("dismiss")
    }
  }
}

let handler = Handler()
Foo().handleAction = handler.handle(_:)

有更好的解决方案吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)