0
我不确定如何进行以下工作。 (Swift 3,XCode8)。Swift 3中的泛型强制
我想制作一个通用节点类,它将状态对象和/或线框对象作为通用参数与状态对象的协议约束为NodeState。
我得到以下错误:
Cannot convert value of type Node<State, Wireframe> to type Node<_,_> in coercion
用下面的代码(应在游乐场工作):
import Foundation
public protocol NodeState {
associatedtype EventType
associatedtype WireframeType
mutating func action(_ event: EventType, withNode node: Node<Self, WireframeType>)
}
extension NodeState {
mutating public func action(_ event: EventType, withNode node: Node<Self, WireframeType>) { }
}
public class Node<State: NodeState, Wireframe> {
public var state: State
public var wireframe: Wireframe?
public init(state: State, wireframe: Wireframe?) {
self.state = state
guard wireframe != nil else { return }
self.wireframe = wireframe
}
public func processEvent(_ event: State.EventType) {
DispatchQueue.main.sync { [weak self] in
// Error presents on the following
let node = self! as Node<State, State.WireframeType>
self!.state.action(event, withNode: node)
}
}
}
任何帮助将不胜感激。谢谢!
UPDATE:
以下工作 - 当我删除了线框引用:
import Foundation
public protocol NodeState {
associatedtype EventType
mutating func action(_ event: EventType, withNode node: Node<Self>)
}
extension NodeState {
mutating public func action(_ event: EventType, withNode node: Node<Self>) { }
}
public class Node<State: NodeState> {
public var state: State
public init(state: State) {
self.state = state
}
public func processEvent(_ event: State.EventType) {
DispatchQueue.main.sync { [weak self] in
self!.state.action(event, withNode: self!)
}
}
}
现在,如何添加选项添加一个通用的线框对象到Node类?
为什么你需要一个单独的'Wireframe'泛型参数?你不能只在类中使用'State.WireframeType'类型吗? – Hamish
感谢Hamish,这是有效的。 –