21

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

For instance

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

Searching yielded nothing.

Clay Bridges
  • 11,602
  • 10
  • 68
  • 118
  • 1
    given that we [can't even use introspection to determine the type of an object](http://stackoverflow.com/questions/24101450/how-do-you-find-out-the-type-of-an-object-in-swift), I doubt there is a swift equivalent - starring though, because if you find a solution, that would provide at least a starting point on my introspection question ;) – Jiaaro Jun 27 '14 at 16:58
  • 1
    Why do you need this? Can you explain the context? There might be a good Swift alternative for what you are trying to do. – Stefan Arentz Jun 29 '14 at 15:49
  • @St3fan I think it's a good question anyway, but for context, cf. first code block in [this SO answer](http://stackoverflow.com/a/24456115/45813) – Clay Bridges Jul 01 '14 at 16:26
  • 2
    Upvoted this because AFAIK there doesn't seem to be any way to initialize `NSValue` with custom structs right now. – John Estropia Sep 29 '14 at 02:09

1 Answers1

6

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.

AlBlue
  • 23,254
  • 14
  • 71
  • 91