Search code examples
swiftcallbackassociated-types

Self as argument type of generic callback


I'm trying to implement generic broadcasting function for each type that supports specific protocol. For example:

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...
    }
}

Question is how to implement bc function right?


Solution

  • i think swift is buggy at this place. maybe you can use

    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...
        }
    }