簡體   English   中英

自我作為通用回調的參數類型

[英]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功能?

我認為在這個地方雨后春筍般的越野車。 也許你可以使用

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM