Self 作为通用回调的参数类型

Self as argument type of generic callback

我正在尝试为支持特定协议的每种类型实现通用广播功能。例如:

protocol Proto {
    typealias ItemType
    typealias Callback = (Self, ItemType)

    func register(tag: String, cb: Callback)
    func unregister(tag: String)
}

class Foo : Proto {
    typealias ItemType = Int

    func register(tag: String, cb: (Foo, Int)) {

    }

    func unregister(tag: String) {

    }
}

func bc <T: Proto> (p: T, value: T.ItemType, os: [String: T.Callback]) {
    for (k, v) in os {
        v(p, value) // error: cannot invoke v with argument list of...
    }
}

问题是如何实现bc功能对吗?

我认为 swift 这个地方有问题。也许你可以使用

protocol Proto {
    typealias ItemType

    func register(tag: String, cb: (Self, Self.ItemType)->())
    func unregister(tag: String, cb: (Self, Self.ItemType)->())
}

class Foo : Proto {

    func register(tag: String, cb: (Foo, Int)->()) {

    }
    func unregister(tag: String, cb: (Foo, Int)->()) {

    }
}

func bc <T: Proto> (p: T, value: T.ItemType, os: [String : (T,T.ItemType)->()]) {
    for (_, vc) in os {
        vc(p, value) // error: cannot invoke v with argument list of...
    }
}