---
title: "encode(to:)"
framework: swift
role: symbol
role_heading: Instance Method
path: "swift/dictionary/encode(to:)"
---

# encode(to:)

Encodes the contents of this dictionary into the given encoder.

## Declaration

```swift
func encode(to encoder: any Encoder) throws
```

## Parameters

- `encoder`: The encoder to write data to.

## Discussion

Discussion If the dictionary uses keys that are String, Int, or a type conforming to CodingKeyRepresentable, the contents are encoded in a keyed container. Otherwise, the contents are encoded as alternating key-value pairs in an unkeyed container. This function throws an error if any values are invalid for the given encoder’s format.

## See Also

### Encoding and Decoding

- [init(from:)](swift/dictionary/init(from:)-6e6js.md)
