我一直在为这个问题苦苦思索
我正在尝试在 Swift 上创建一个绑定(bind)结构,以一种简单的方式绑定(bind) viewModel 和 Controller 。所以我创建了一个协议(protocol)来定义要存储在 Controller 上的变量。
protocol DVA_MOVVER_ViewControllerProtocolDelegate {
associatedtype delegateType : DVA_MOVVER_ViewModelProtocol
var dva_viewModelDelegate : delegateType? { get set }
}
如您所见,该变量仅限于实现另一个协议(protocol),即这个协议(protocol):
protocol DVA_MOVVER_ViewControllerProtocol {
func dva_tellViewModel()
// Some other methods
}
我希望 Controller 类只实现变量,所以它可以是一个存储变量。我无法使用扩展来完成。
所以,我有第二个协议(protocol)的扩展来实现绑定(bind)并创建一个通用方法来将变量绑定(bind)到 Controller
extension DVA_MOVVER_ViewControllerProtocol where Self:DVA_MOVVER_ViewControllerProtocolDelegate {
mutating func dva_bindViewModel<T:DVA_MOVVER_ViewModelProtocol>(parameter:T) {
typealias delegateType = T
self.dva_viewModelDelegate = parameter
}
...
// The rest of the DVA_MOVVER_ViewControllerProtocol methods
}
这就是我卡住的地方。编译器说“无法将类型‘T’的值分配给类型‘_?’”。我假设这可能是因为它无法在编译时解析参数类型,但我不知道如何解决这个......
最佳答案
如 @rbarbera 所述,类型删除是这种情况下的方法:
关于ios - 无法将通用值分配给扩展中的协议(protocol) associatedType 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37762451/