Create an Array in Swift from an NSData Object

后端 未结 4 1061
说谎
说谎 2020-12-13 09:13

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

4条回答
  •  无人及你
    2020-12-13 10:06

    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.

提交回复
热议问题