Swift 3 version of creating a string from a pointer, length and encoding?


(John Brownie) #1

Next question in my migration. How do I do what this did in Swift 2.2?

let theData = String.init(bytes: data.memory, length: length, encoding: NSUTF8StringEncoding)

The only initialisers that have a length are

init?(bytesNoCopy: UnsafeMutableRawPointer, length: Int, encoding: String.Encoding, freeWhenDone: Bool)
init(utf16CodeUnitsNoCopy: UnsafePointer<unichar>, count: Int, freeWhenDone: Bool)

Neither is applicable.

Do I need to push it into a Data object first, like this?

let theData = String.init(data: Data.init(bytes: data, length: length), encoding: String.Encoding.utf8)

Or is there a better way that I've missed (highly possible)?

John

···

--
John Brownie
In Finland on furlough from SIL Papua New Guinea


(Quinn “The Eskimo!”) #2

I don’t think there’s anything significantly better. The other two options I can think of:

* use the `UTF8` codec

* use NSString

NSString(bytes: bytes, length: length, encoding: String.Encoding.utf8.rawValue) as? String

Honestly, I think bouncing through `Data` is better.

Share and Enjoy

···

On 29 Sep 2016, at 10:47, John Brownie via swift-users <swift-users@swift.org> wrote:

Or is there a better way that I've missed (highly possible)?

--
Quinn "The Eskimo!" <http://www.apple.com/developer/>
Apple Developer Relations, Developer Technical Support, Core OS/Hardware