macu macu - 7 months ago 41
Swift Question

Swift - converting from UnsafePointer<UInt8> with length to String

I considered a lot of similar questions, but still can't get the compiler to accept this.

Socket Mobile API (in Objective-C) passes ISktScanDecodedData into a delegate method in Swift (the data may be binary, which I suppose is why it's not provided as string):

func onDecodedData(device: DeviceInfo?, DecodedData d: ISktScanDecodedData?) {
let symbology: String = d!.Name()
let rawData: UnsafePointer<UInt8> = d!.getData()
let rawDataSize: UInt32 = decoded!.getDataSize()
// want a String (UTF8 is OK) or Swifty byte array...
}


In C#, this code converts the raw data into a string:

string s = Marshal.PtrToStringAuto(d.GetData(), d.GetDataSize());


In Swift, I can get as far as
UnsafeArray
, but then I'm stuck:

let rawArray = UnsafeArray<UInt8>(start: rawData, length: Int(rawDataSize))


Alternatively I see
String.fromCString
and
NSString.stringWithCharacters
, but neither will accept the types of arguments at hand. If I could convert from
UnsafePointer<UInt8>
to
UnsafePointer<()>
, for example, then this would be available (though I'm not sure if it would even be safe):

NSData(bytesNoCopy: UnsafePointer<()>, length: Int, freeWhenDone: Bool)


Is there an obvious way to get a string out of all this?

Answer

This should work:

let data = NSData(bytes: rawData, length: Int(rawDataSize))
let str = NSString(data: data, encoding: NSUTF8StringEncoding)