我编写了我遇到问题的类似实现的简化版本。任何人都知道为什么会这样,最终如何解决?
注意:代码只是示例,以使其尽可能简单
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/