Swift equivalent of @encode

2020-05-22 06:41发布

问题:

Is there a Swift equivalent to Objective-C's @encode?

For instance

@encode(void *) // -> @"^v"

Searching yielded nothing.

回答1:

No, there isn't - because under the hood Swift classes don't use Objective-C introspection to do their work. There's no need to calculate this (like there is in Objective-C) in order to pass/call data.

However, if you need to use it dynamically at runtime (say, for interoperation with existing Objective-C methods) then you can either create an Objective-C call and pass the object through or (for simple types) write a lookup table.

The type encodings are listed at https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html which have the map, and it's possible to write a switch type statement that does the lookup.

But fundamentally if you have a type that you want to pass in and find it's objective c encoding type, you can use the NSObject's objCType method:

var i = 1 as NSNumber
String.fromCString(i.objCType)! == "q" 

If you need to pass it through as an unmolested C string anyway, you may not even need to convert it back to a Swift string type.