ZIP Compression Implementation in Swift
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓ZIP Compression runs in O(n) time and O(n) space, in Swift as in every other language.
- ✓Foundation has no ZIP container. Apple ships the codec instead: the Compression framework (compression_encode_buffer, the compression_stream_* family) with COMPRESSION_ZLIB, plus Foundation's bridged (data as NSData).compressed(using: .zlib).
- ✓Reviewers insist the pointer from Data.withUnsafeBytes never escapes its closure and that nothing inside the closure can mutate the same Data.
- ✓The Swift trap: COMPRESSION_ZLIB is documented as producing RAW DEFLATE, RFC 1951, with no two-byte zlib header and no adler32 trailer.
- ✓compression_encode_buffer returns 0 both for genuine failure and for "the result did not fit", so safe sizing means over-allocating the destination, which the streaming API avoids; reusing a scratch buffer sized by compression_encode_scratch_buffer_size removes the per-call allocation entirely.
What ZIP Compression actually is
ZIP Compression in Swift: what you actually reach for
Swift implementation
import Foundation
import Compression
enum ZipDeflate {
/// COMPRESSION_ZLIB emits RAW DEFLATE (RFC 1951): no zlib header,
/// no adler32 trailer. That is precisely ZIP method 8.
static func deflate(_ input: Data) -> Data? {
guard !input.isEmpty else { return nil }
// DEFLATE EXPANDS incompressible input: about 5 bytes per stored
// block (measured 1,000,000 -> 1,000,305 with COMPRESSION_ZLIB),
// so 64 bytes of slack is not safe sizing.
let capacity = max(input.count + input.count / 1000 + 64, 4096)
let dst = UnsafeMutablePointer<UInt8>.allocate(capacity: capacity)
defer { dst.deallocate() }
let written = input.withUnsafeBytes { raw -> Int in
guard let base = raw.bindMemory(to: UInt8.self).baseAddress else {
return 0
}
return compression_encode_buffer(dst, capacity,
base, input.count,
nil, COMPRESSION_ZLIB)
}
// 0 means failed OR did not fit; there is no separate signal.
guard written > 0 else { return nil }
return Data(bytes: dst, count: written)
}
/// A slice keeps its parent's indices: never assume startIndex == 0.
static func firstByte(of slice: Data) -> UInt8? {
slice.isEmpty ? nil : slice[slice.startIndex]
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Swift-specific trap
Performance in Swift, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Swift type or library should I use for ZIP Compression?
Foundation has no ZIP container. Apple ships the codec instead: the Compression framework (compression_encode_buffer, the compression_stream_* family) with COMPRESSION_ZLIB, plus Foundation's bridged (data as NSData).compressed(using: .zlib). On macOS and iOS there is also a whole-directory shortcut, NSFileCoordinator reading with the .forUploading option, which hands back a temporary URL that is a ZIP when the item is a directory or package. For entry-level control the community package is ZIPFoundation: import ZIPFoundation gives Archive, addEntry, extract, and FileManager.zipItem/unzipItem. AppleArchive is Apple's own AAR format, not ZIP.
What is the most common Swift mistake when implementing ZIP Compression?
COMPRESSION_ZLIB is documented as producing RAW DEFLATE, RFC 1951, with no two-byte zlib header and no adler32 trailer. That is exactly ZIP method 8, so it drops straight into a local file header, but the identical bytes fail in anything expecting genuinely zlib-wrapped data, and it is not gzip either. The second Swift-only trap is that a Data slice keeps its parent's indices: on a slice beginning at offset 100, slice[0] traps with index out of range, while withUnsafeBytes on that same slice hands you a pointer to the slice's own first byte. Every hand-rolled header parser written over Data sub-ranges hits that disagreement.
How does ZIP Compression actually perform in Swift?
compression_encode_buffer returns 0 both for genuine failure and for "the result did not fit", so safe sizing means over-allocating the destination, which the streaming API avoids; reusing a scratch buffer sized by compression_encode_scratch_buffer_size removes the per-call allocation entirely. ARC is the other constant: appending to a Data inside a loop copies on write whenever another reference is still alive, so build into one Data with reserveCapacity up front. Bridging through NSData retains and may copy the backing store. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Devin free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.