<!--
{
  "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/NSCoder/decodeTopLevelObject(of:forKey:)-3w6pd",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Foundation"
    ],
    "preciseIdentifier" : "s:So7NSCoderC10FoundationE20decodeTopLevelObject2of6forKeyxSgxm_SStKSo8NSObjectCRbzSo8NSCodingRzlF"
  },
  "title" : "decodeTopLevelObject(of:forKey:)"
}
-->

# decodeTopLevelObject(of:forKey:)

Decode an object as one of several expected types, failing if the archived type does not match.

```
func decodeTopLevelObject<DecodedObjectType>(of cls: DecodedObjectType.Type, forKey key: String) throws -> 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 the following cases:

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

If the coder does not 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)