[swift-users] changes to pointer data types in Xcode 8 beta 6
davelist at mac.com
davelist at mac.com
Mon Aug 15 17:05:30 CDT 2016
I'm trying to convert the following code (from the Big Nerd Ranch's Freddy JSON parser) that works in Xcode 8 beta 5 and convert it to work with beta 6. Essentially it appears it needs to take a Data object and convert it to a UnsafeBufferPointer<UInt8> if I understand it correctly.
/// Creates a `JSONParser` ready to parse UTF-8 encoded `NSData`.
///
/// If the data is mutable, it is copied before parsing. The data's lifetime
/// is extended for the duration of parsing.
init(utf8Data inData: Data) {
let data = (inData as NSData).copy() as! Data
let buffer = UnsafeBufferPointer(start: UnsafePointer<UInt8>((data as NSData).bytes), count: data.count)
self.init(buffer: buffer, owner: data)
}
And this case appears to be going from a String to UnsafeBufferPointer<Uint8>
/// Creates a `JSONParser` from the code units represented by the `string`.
///
/// The synthesized string is lifetime-extended for the duration of parsing.
init(string: String) {
let codePoints = string.nulTerminatedUTF8
let buffer = codePoints.withUnsafeBufferPointer { nulTerminatedBuffer in
// don't want to include the nul termination in the buffer - trim it off
UnsafeBufferPointer(start: nulTerminatedBuffer.baseAddress, count: nulTerminatedBuffer.count - 1)
}
self.init(buffer: buffer, owner: codePoints)
}
}
I understand pointers from my C/C++/Objective-C days but I don't yet understand the various Swift pointer types. Any help is appreciated.
Note: I don't work for Big Nerd Ranch. I'm just trying to use the code and better understand the various Swift pointer types.
Thanks,
Dave Reed
More information about the swift-users
mailing list