<!--
{
  "availability" : [
    "iOS: 9.0.0 -",
    "iPadOS: 9.0.0 -",
    "macCatalyst: 9.0.0 -",
    "macOS: 10.11.0 -",
    "tvOS: 9.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 2.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Foundation",
  "identifier" : "/documentation/Foundation/NSKeyedArchiver/encodeEncodable(_:forKey:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Foundation"
    ],
    "preciseIdentifier" : "s:So15NSKeyedArchiverC10FoundationE15encodeEncodable_6forKeyyx_SStKSERzlF"
  },
  "title" : "encodeEncodable(_:forKey:)"
}
-->

# encodeEncodable(_:forKey:)

Encodes a given value and associates it with a key.

```
@nonobjc func encodeEncodable<T>(_ value: T, forKey key: String) throws where T : Encodable
```

## Parameters

`value`

The value to encode.

`key`

The key with which to associate the encoded value.

## Discussion

If there’s a problem encoding the value you supply, this method throws an error based on the type of problem:

- The value fails to encode, or contains a nested value that fails to encode—this method throws the corresponding error.
- The value can’t be encoded as a property list—this method throws the <doc://com.apple.documentation/documentation/Swift/EncodingError/invalidValue(_:_:)> error.

---

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)