Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift equivalent of @encode

Tags:

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

For instance

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

Searching yielded nothing.

like image 905
Clay Bridges Avatar asked Jun 27 '14 16:06

Clay Bridges


People also ask

What is string encoding in Swift?

Overview. A string is a series of characters, such as "Swift" , that forms a collection. Strings in Swift are Unicode correct and locale insensitive, and are designed to be efficient. The String type bridges with the Objective-C class NSString and offers interoperability with C functions that works with strings.

What is encoding and decoding in Swift?

But before you can do that, you need to convert the data to a suitable format through a process called encoding or serialization. You'll also need to convert the saved data sent over the network to a suitable format before using it in your app. This reverse process is called decoding or deserialization.


1 Answers

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.

like image 165
AlBlue Avatar answered Sep 28 '22 16:09

AlBlue