通用类的Swift委托协议

Stu*_*art 7 generics delegates protocols swift

我有一个类,StateMachine它是通用的,允许实现不同的状态集,例如,枚举.我想StateMachineDelegate在状态机进入新状态时使用协议通知委托.

但这不起作用,因为委托协议对于类型要求也是通用的.该错误显示了delegate声明属性的位置.

protocol StateType: Hashable {}

protocol StateMachineDelegate: class {
    typealias S: StateType
    func stateMachine(stateMachine: StateMachine<S>, didEnterState newState: S)
}

class StateMachine<S: StateType> {
    typealias State = S

    weak var delegate: StateMachineDelegate?
    //~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~
    //Protocol 'StateMachineDelegate' can only be used as a generic constraint because it has Self or associated type requirements

    var currentState: State {...}

    init(initialState: State) {...}

    func applyState(toState: State) -> Bool {
        ...
        currentState = toState
        delegate?.stateMachine(self, didEnterState: toState)
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)



我需要以某种方式将其StateMachineDelegate.S == SStateMachine课堂相关联,但我不确定如何做到这一点,或者是否可能.我试过了:

class StateMachine<S: StateType, D: StateMachineDelegate where D.S == S> {
    ...
    weak var delegate: D?
    ...
}
Run Code Online (Sandbox Code Playgroud)

但后来我试图重新修改协议以正确声明泛型类型StateMachine.在创建一个代码时,必须事先声明委托的类型似乎是不对的StateMachine.

Mat*_*mbo 0

我认为这只是一个名称冲突问题......试试这个:

protocol StateType: Hashable {}

protocol StateMachineDelegate: class {
    typealias State: StateType
    func stateMachine(stateMachine: StateMachine<State>, didEnterState newState: State)
}

class StateMachine<S: StateType> {
    typealias State = S

    weak var delegate: StateMachineDelegate?


    var currentState: State {...}

    init(initialState: State) {...}

    func applyState(toState: State) -> Bool {
        ...
            currentState = toState
        delegate?.stateMachine(self, didEnterState: toState)
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

您需要声明协议中定义的泛型类型的名称应该在符合它的类中。