[swift-users] unsafeBitCast to Unimplemented Class
Andrew Trick
atrick at apple.com
Wed Feb 8 02:37:30 CST 2017
> On Feb 7, 2017, at 3:44 PM, Dave Abrahams via swift-users <swift-users at swift.org> wrote:
>
>>
>> I phrased that as a question because I'm the last person who should be
>> giving advice here... What I had in mind is this:
>>
>> if ([self isKindOfClass:NSClassFromString(@“Bar”)]) {
>> self.perform(@selector(FakeBarProtocol.foo))
>> }
>>
>> It's not type safe, but it's a lot better than outright lying about
>> the reference's dynamic type.
>
> Presumably there's a way to express that in Swift, but if it uses
> varargs I expect it's pretty darned inefficient.
>
> --
> -Dave
Um, this is the untyped dispatch in Swift:
>> self.perform(@selector(FakeBarProtocol.foo))
It just wraps a string literal up and sends it to NSObject.perform.
I didn’t get around to rewriting the line above it in Swift...
> if ([self isKindOfClass:NSClassFromString(@“Bar”)]) {
Which is now the next question...
> Also, class_getName(_:) seems to return a UnsafePointer<Int8>, is this just a C-style string? Should I use this over NSStringFromClass or isKindOfClass?
Yes, it returns “raw” C string as an UnsafePointer. I really don’t know these API's, but the other two you mention would seem to avoid Unsafe code. That’s a good thing.
> Yep, it’s not–that’s why I need to go through this trouble :) My plugin is loaded at runtime, so the headers are the best I’ve got (though if you’ve got a way to perform a stricter check, I’m all ears!) Until then, all of these methods appear to be sugarcoating around perform(selector:)–is there any “preferred” way to do this?
>
I would guess that the right way to do this is to declare an ObjC protocol that will be imported via a bridging header. Whatever types are defined by your plugin should just conform to that protocol.
Beyond that, I’ll have to appeal to others on the list for suggestions.
-Andy
More information about the swift-users
mailing list