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

# decodeTopLevelObject(of:forKey:)

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

```
@nonobjc func decodeTopLevelObject(of classes: [AnyClass]?, forKey key: String) throws -> Any?
```

## Parameters

`classes`

An array of expected classes that the object being decoded should match at least one of.

`key`

The key indicating the member to decode.

## Return Value

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

## Discussion

This method is equivalent to [`decodeObject(of:forKey:)`](/documentation/Foundation/NSCoder/decodeObject(of:forKey:)-7tmft), but allows you to specify a set of classes that the decoded object can match. If [`requiresSecureCoding`](/documentation/Foundation/NSCoder/requiresSecureCoding) is `true`, the decoded object’s class must be a member of the classes parameter, or a sublcass of a member.

---

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)