Last edit
Added:
> Update 2016-10-06; a very nice (and updated for Swift 3) blog about this: http://technology.meronapps.com/2016/09/27/swift-3-0-unsafe-world-2/
Update 2016-10-06; a very nice (and updated for Swift 3) blog about this: http://technology.meronapps.com/2016/09/27/swift-3-0-unsafe-world-2/
I couldn't find a nice example for Array<T>.withUnsafeBufferPointer, so here's one which you can paste right into a Playground:
//: Playground - noun: a place where people can play
import UIKit
var buf = [UInt8](count: 10, repeatedValue: 0)
// Fill buffer with A to J
for (var i = 0; i < buf.count; i++) {
buf[i] = 65 + UInt8(i) // 65 = A
} // Calculate pointer to print contents
buf.withUnsafeBufferPointer { (pbuf: UnsafeBufferPointer<UInt8>) -> UnsafePointer<UInt8> in for (var j = 0; j < pbuf.count; j++) {
let p = pbuf.baseAddress
print(Character(UnicodeScalar((p+j).memory)))
println(String(format:" = 0x%X", (p+j).memory))
}
return nil
}Output:
A = 0x41 B = 0x42 C = 0x43 D = 0x44 E = 0x45 F = 0x46 G = 0x47 H = 0x48 I = 0x49 J = 0x4A