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
Here is a generic way to do it.
import Foundation
extension Data {
func elements () -> [T] {
return withUnsafeBytes {
Array(UnsafeBufferPointer(start: $0, count: count/MemoryLayout.size))
}
}
}
let array = [1, 2, 3]
let data = Data(buffer: UnsafeBufferPointer(start: array, count: array.count))
let array2: [Int] = data.elements()
array == array2
// IN THE PLAYGROUND, THIS SHOWS AS TRUE
You must specify the type in the array2 line. Otherwise, the compiler cannot guess.