2

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) ?

D. Wang
  • 165
  • 1
  • 9
  • Are you using a specific gzip library? What is your issue exactly? – Eric Aya Jun 16 '17 at 09:30
  • Eric, Thanks for your reply. As I'm new to Swift, I don't really know how to GZIP an array of integers in Swift on iOS. I searched the internet and found GzipSwift (https://github.com/1024jp/GzipSwift). I created a podfile and install the framework in my project, but still don't know how to use it do my task. Can you shade some light on it? – D. Wang Jun 16 '17 at 11:55
  • 1
    If you look at the very fist example on this library's page, you can see that it's very easy to call .gzipped() on data and .gunzipped() on compressed data. So your issue would be only to transform the array into data. For that, you can refer to https://stackoverflow.com/a/38024025/2227743 – Eric Aya Jun 16 '17 at 12:13
  • 1
    `why the compressed data is ... 3 times larger than the row data` The data you are compressing is very small and has no redundancy. I'd bet that not only it's not compressible but that gzip adds metadata/headers to the data payload (needed for unzipping), making it bigger than the uncompressed data: it has the data + metadata. Try with big arrays containing at least some redundancy, it should behave as expected. – Eric Aya Jun 16 '17 at 20:20

0 Answers0