I'm trying to store an array of integers to disk in swift. I can get them into an NSData object to store, but getting them back out into an array is difficult. I can get a raw COpaquePointer
to the data with data.bytes
but can't find a way to initialize a new swift array with that pointer. Does anyone know how to do it?
import Foundation
var arr : UInt32[] = [32,4,123,4,5,2];
let data = NSData(bytes: arr, length: arr.count * sizeof(UInt32))
println(data) //data looks good in the inspector
// now get it back into an array?
It's also possible to do this using an
UnsafeBufferPointer
, which is essentially an "array pointer", as it implements theSequence
protocol:This eliminates the need for initializing an empty array with duplicated elements first, to then overwrite it, although I have no idea if it's any faster. As it uses the
Sequence
protocol this implies iteration rather than fast memory copy, though I don't know if it's optimized when passed a buffer pointer. Then again, I'm not sure how fast the "create an empty array with X identical elements" initializer is either.You can use the
getBytes
method ofNSData
:Update for Swift 3 (Xcode 8): Swift 3 has a new type
struct Data
which is a wrapper forNS(Mutable)Data
with proper value semantics. The accessor methods are slightly different.Array to Data:
Data to Array:
If you are dealing with Data to Array (I know for sure my array is going to be [String]), I am quite happy with this:
NSKeyedUnarchiver.unarchiveObject(with: yourData)
I hope it helps
Here is a generic way to do it.
You must specify the type in the
array2
line. Otherwise, the compiler cannot guess.