Dave Dave - 1 year ago 75
Swift Question

Converting a C string inside a struct to a Swift String

I am using an existing C library in a Swift app and trying to convert a C character buffer to a Swift String.


typedef struct { char mfg[8]; char model[8]; } motorcycle;

void GetMotorcycle(motorcycle *m);


var cycle = motorcycle(mfg: (0,0,0,0,0,0,0,0), model: (0,0,0,0,0,0,0,0));
var manufacturer : String = String.fromCString(cycle.mfg) // Error

This produces "Could not find a overload for 'fromCString' that accepts the supplied arguments"

Since Swift treats the C character array as a tuple, I cannot find a way to convert it to a Swift String.

Answer Source

Well, at least that C character array is only eight characters long, since there's currently no way to iterate over a tuple. Here's how you can convert it:

func char8ToString(tuple: (CChar, CChar, CChar, CChar, CChar, CChar, CChar, CChar)) -> String {
    let arr: unichar[] = [unichar(tuple.0), unichar(tuple.1),
                        unichar(tuple.2), unichar(tuple.3),
                        unichar(tuple.4), unichar(tuple.5),
                        unichar(tuple.6), unichar(tuple.7)]
    let len = arr.reduce(0) { $1 != 0 ? $0 + 1 : $0 }
    return NSString(characters: arr, length: len)

var manufacturer: String = char8ToString(cycle.mfg)

Hopefully we get language support for a better way to handle this case soon!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download