I am new to Swift. I'd like to know how to GZIP an array of integers. I would appreciate it if you could provide an example.
Assuming that I have an array containing Int16 integers as below. Please explain how to compress it and then uncompress the gzipped bytes back.
let array:[Int16] = [1,2,3,4,5]
Thanks!
Here is what I have tried, but got very strange results.
Code:
let array: [Int16] = [1,2,3,4,5]
let arrayData = Data(fromArray: array)
let compData = try! arrayData.gzipped()
let decomp_array = try! compData.gunzipped()
let array_1: [Int16] = decomp_array.toArray(type: Int16.self)
print("array: \(array)")
print("arrayData: \(arrayData)")
print("compData: \(compData)")
print("decomp_array: \(decomp_array)")
print("array_1: \(array_1)")
extension Data {
    init<T>(fromArray values: [T]) {
        var values = values
        self.init(buffer: UnsafeBufferPointer(start: &values, count: 
        values.count)) }
    func toArray<T>(type: T.Type) -> [T] {
        return self.withUnsafeBytes {
           [T](UnsafeBufferPointer(start: $0, count: 
            self.count/MemoryLayout<T>.stride))
        }
    }
}
Result:
array: [1, 2, 3, 4, 5]
arrayData: 10 bytes
compData: 30 bytes
decomp_array: 10 bytes
array_1: [1, 2, 3, 4, 5]
Update:
I now have correct results after gzip/gunzip, but why the compressed data is 30 bytes (3 times larger than the row data) ?
