<!--
{
  "availability" : [
    "iOS: 13.0.0 -",
    "iPadOS: 13.0.0 -",
    "macCatalyst: 13.1.0 -",
    "macOS: 10.15.0 -",
    "tvOS: 13.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 6.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Foundation",
  "identifier" : "/documentation/Foundation/NSMutableData/compress(using:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Foundation"
    ],
    "preciseIdentifier" : "c:objc(cs)NSMutableData(im)compressUsingAlgorithm:error:"
  },
  "title" : "compress(using:)"
}
-->

# compress(using:)

Compresses the data object’s bytes using an algorithm that you specify.

```
func compress(using algorithm: NSData.CompressionAlgorithm) throws
```

## Parameters

`algorithm`

The algorithm to use to compress the data. For a list of available algorithms, see [`NSData.CompressionAlgorithm`](/documentation/Foundation/NSData/CompressionAlgorithm).

## Discussion

Use this method to compress in-memory data when you want to reduce memory usage and can afford the time to compress and decompress the data. If your data object is already in a compressed format, such as media formats like JPEG images or AAC audio, [`compress(using:)`](/documentation/Foundation/NSMutableData/compress(using:)) may provide minimal or no benefit.

The following example shows how to compress data from a string and prints the sizes of the data instances to illustrate the amount of compression:

```swift
var string = "NSData and its mutable subclass NSMutableData provide data objects, or object-oriented wrappers for byte buffers. Data objects let simple allocated buffers (that is, data with no embedded pointers) take on the behavior of Foundation objects."
let data = NSMutableData(data: Data(string.utf8))
print ("original data size: \(data.length)")
do {
    try data.compress(using: .zlib)
    print("zlib compressed size: \(data.length)")
} catch {
    print ("Compression error: \(error)")
}
// Prints:
//  original data size: 241
//  zlib compressed size: 158
```

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)