<!--
{
  "availability" : [
    "iOS: 8.0.0 -",
    "iPadOS: 8.0.0 -",
    "macCatalyst: 8.0.0 -",
    "macOS: 10.10.0 -",
    "tvOS: 9.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 2.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Foundation",
  "identifier" : "/documentation/Foundation/NSCoder/decodeObject(of:forKey:)-7tmft",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Foundation"
    ],
    "preciseIdentifier" : "s:So7NSCoderC10FoundationE12decodeObject2of6forKeyxSgxm_SStSo8NSObjectCRbzSo8NSCodingRzlF"
  },
  "title" : "decodeObject(of:forKey:)"
}
-->

# decodeObject(of:forKey:)

Decode an object as an expected type, failing if the archived type doesn’t match.

```
func decodeObject<DecodedObjectType>(of cls: DecodedObjectType.Type, forKey key: String) -> DecodedObjectType? where DecodedObjectType : NSObject, DecodedObjectType : NSCoding
```

## Parameters

`cls`

The expected class of the object being decoded.

`key`

The key indicating the member to decode.

## Return Value

The decoded object, or `nil` if decoding fails.

## Discussion

If the coder responds <doc://com.apple.documentation/documentation/Swift/true> to [`requiresSecureCoding`](/documentation/Foundation/NSCoder/requiresSecureCoding), then the coder calls [`failWithError(_:)`](/documentation/Foundation/NSCoder/failWithError(_:)) in either of the following cases:

- The class indicated by `cls` doesn’t implement [`NSSecureCoding`](/documentation/Foundation/NSSecureCoding).
- The unarchived class doesn’t match `cls`, nor do any of its superclasses.

If the coder doesn’t require secure coding, it ignores the `cls` parameter and does not check the decoded object.

---

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)