Swift 3

时间:2016-10-11 09:53:42

标签: generics type-conversion swift3 swift-protocols type-alias

我不确定如何进行以下工作。 (Swift 3,XCode8)。

我正在尝试创建通用Node类,它将状态对象和/或线框对象作为通用参数,状态对象具有作为NodeState的协议约束。

我收到以下错误:

Cannot convert value of type Node<State, Wireframe> to type Node<_,_> in coercion 

使用以下代码(应该在Playground中运行):

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)

        }

    }

}

非常感谢任何帮助。谢谢!

更新:

以下工作 - 当我删除线框引用时:

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!)

        }

    }

}

现在,如何添加将通用Wireframe对象添加到Node类的选项?

1 个答案:

答案 0 :(得分: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!)

        }

    }

}