2015-06-20 56 views
1

我试图为支持特定协议的每种类型实现泛型广播函数。例如:自我作为泛型回调的参数类型

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功能吧?

+0

你是否试图调用'T.Callback'的初始化程序? – ABakerSmith

+0

不,只是关闭。例如,'v'是对封闭的引用,添加在Foo.register中。目标是用相同的参数调用每个注册的回调。 – HeMet

回答

1

我认为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... 
    } 
} 
+0

它的工作原理,感谢解决方法。主要缺点是它使你复制过去的类型定义。 – HeMet