aleclarson / emitter-kit

Type-safe event handling for Swift
MIT License
567 stars 71 forks source link

Protocol casting fails #60

Closed kamzab95 closed 5 years ago

kamzab95 commented 5 years ago

There is specific case when calling event.emit(*) causes critical error. It happens when event is expecting type protocol.

init (_ event: Event<T>, _ target: AnyObject!, _ once: Bool, _ handler: @escaping (T) -> Void) {
    self.event = event
    super.init(target, once, {
        handler($0 as! T) <- Error while casting
    })
}

(Issue appeared after migration of the own project to swift 4.2)

kamzab95 commented 5 years ago

Solution: Casting to protocol has something to do with "Swift 3 @objc Interface" which is now deprecated.

https://stackoverflow.com/questions/42033735/failing-cast-in-swift-from-any-to-protocol This thread explains quite well what is the issue and how it can be repaired.

In this case only minor change is required:

init (_ event: Event<T>, _ target: AnyObject!, _ once: Bool, _ handler: @escaping (T) -> Void) {
    self.event = event
    super.init(target, once, {
        handler($0 as AnyObject as! T)
    })
 }