2016-10-11 65 views
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類?

+0

爲什麼你需要一個單獨的'Wireframe'泛型參數?你不能只在類中使用'State.WireframeType'類型嗎? – Hamish

+0

感謝Hamish,這是有效的。 –

回答

0

應用我懷疑的是Hamish的答案,現在按預期編譯。謝謝!

import Foundation 

public protocol NodeState { 

    associatedtype EventType 
    associatedtype WireframeType 

    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 var wireframe: State.WireframeType? 

    public init(state: State, wireframe: State.WireframeType?) { 

     self.state = state 

     guard wireframe != nil else { return } 
     self.wireframe = wireframe 

    } 

    public func processEvent(_ event: State.EventType) { 

     DispatchQueue.main.sync { [weak self] in 

      self!.state.action(event, withNode: self!) 

     } 

    } 

}