<!--
{
  "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/NSData/compressed(using:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Foundation"
    ],
    "preciseIdentifier" : "c:objc(cs)NSData(im)compressedDataUsingAlgorithm:error:"
  },
  "title" : "compressed(using:)"
}
-->

# compressed(using:)

Returns a new data object by compressing the data object’s bytes.

```
func compressed(using algorithm: NSData.CompressionAlgorithm) throws -> Self
```

## Parameters

`algorithm`

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

## Return Value

An [`NSData`](/documentation/Foundation/NSData) instance that contains the compressed buffer data.

## 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 it. If your data object is already in a compressed format, such as media formats like JPEG images or AAC audio, additional compression may provide minimal or no reduction in memory usage.

To restore this data, use [`decompressed(using:)`](/documentation/Foundation/NSData/decompressed(using:)), and specify the algorithm originally used to compress the data.

The following example shows how to compress the 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 = Data(string.utf8) as NSData
print ("original data size: \(data.count) bytes")
do {
    let compressedData = try data.compressed(using: .zlib)
    print("zlib compressed size: \(compressedData.count) bytes")
} catch {
    print ("Compression error: \(error)")
}
// Prints:
//  original data size: 241 bytes
//  zlib compressed size: 158 bytes
```

---

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)