Reputation: 5119
This is a very simple problem to explain, but it's driving me nuts!
I have a generic Event
class:
class Event<T> {
// Etc...
}
On that class I want to add a class function that takes an array of Event
s and returns another generic type (EventListener
):
public class func listenAny<V>(listener: AnyObject, events: [Event<V>]) -> EventListener<V> {
// Etc...
}
For some reason, this code doesn't compile!
let e1 = Event<Int>()
let e2 = Event<Int>()
class Listener {}
let l = Listener()
Event.listenAny(l, events: [e1, e2])
The compiler throws an error on the last line:
Here's a piece of code that you can paste on a Playground (I tested this on a Playground on Xcode 6.1.1) and experience the frustration for yourself:
public class Event<T> {
private var eventListeners = [EventListener<T>]()
public class func listenAny<V>(listener: AnyObject, events: [Event<V>]) -> EventListener<V> {
let eventListener = EventListener<V>(listener: listener)
for event in events { event.addListener(eventListener) }
return eventListener
}
private func addListener(listener: EventListener<T>) -> EventListener<T> {
eventListeners.append(listener)
return listener
}
}
public class EventListener<T> {
weak public var listener: AnyObject?
private init(listener: AnyObject) {
self.listener = listener
}
}
let e1 = Event<Int>()
let e2 = Event<Int>()
class Listener {}
let l = Listener()
let v = [e1, e2]
Event.listenAny(l, events: v)
Why is this not working?
PS: I intend for the array of events to be a variadic parameter. I hope that if I get this to work with an array, I can do the same with a variadic parameter.
PSS: It seems that if I make the listenAny
a global function, it works. It might be a problem with the type system (T from Event in conjunction with V from the function...)
Upvotes: 0
Views: 695
Reputation: 1936
You need to supply the generic type of the class Event. The following code compiles correctly:
Event<Int>.listenAny(l, events: v)
Note: I use Int as the generic type, but you can use any type.
Upvotes: 1