Extension of a generic objective-c class cannot access the class's generic parameters at runtime error?

I'm trying to get some github code to function in Swift 4.1 and Xcode 9.3, but cannot. Presumably the code ran in an earlier version of Swift. It appears the offending code is as follows:


extension GKComponentSystem

{

func getGKAgent2D() -> [GKAgent2D]

{

return components

.filter({ $0 is GKAgent2D })

.map({ $0 as! GKAgent2D })

}

}


When I try to run in simulator for iPhone 8 I get the following error message:

Extension of a generic objective-c class cannot access the class's generic parameters at runtime.


I've done some searching and one source claimed that addition @objc func.... should fix the issue. It does not. I am at a loss. Can anyone give any insight to how to fix the problem? Thanks in advance.

Accepted Reply

Imported Objective-C generics show many odd behaviors in Swift, so I cannot be very sure. But this compiles with Swift 4.1/Xcode 9.3.


extension GKComponentSystem {
    @objc func getGKAgent2D() -> [GKAgent2D] {
        return (components as NSArray)
            .compactMap({ $0 as? GKAgent2D })
    }
}

(Using `compactMap` is not essential here. Just that `filter` and `map` seemed inefficient.)

Replies

Imported Objective-C generics show many odd behaviors in Swift, so I cannot be very sure. But this compiles with Swift 4.1/Xcode 9.3.


extension GKComponentSystem {
    @objc func getGKAgent2D() -> [GKAgent2D] {
        return (components as NSArray)
            .compactMap({ $0 as? GKAgent2D })
    }
}

(Using `compactMap` is not essential here. Just that `filter` and `map` seemed inefficient.)

Thanks. Got things working after doing your above, and making a few additional "Selector("step") to #selector(step) type changes. Tried both the .compactMap and the original .filter and .map code. Both work, 'seemingly' the same, but I did not do any serious testing. Can't say I truely understand all the coding at this point. Was trying to learn from using and setting breakpoints, etc. I can't seem to get any breakpoints to work in this demo. I can 'set' them, but the code never stops at them. I think it may have something to do with a CADisplayLink that triggers a step function.

Anyway, you are a steely eyed missle man OOPer! Thanks much. I'll mark it as Correct Answer.