<!--
{
  "availability" : [
    "iOS: 2.0.0 -",
    "iPadOS: 2.0.0 -",
    "macCatalyst: 13.0.0 -",
    "macOS: 10.0.0 -",
    "tvOS: 9.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 2.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Foundation",
  "identifier" : "/documentation/Foundation/NSMutableDictionary/setObject(_:forKey:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Foundation"
    ],
    "preciseIdentifier" : "c:objc(cs)NSMutableDictionary(im)setObject:forKey:"
  },
  "title" : "setObject(_:forKey:)"
}
-->

# setObject(_:forKey:)

Adds a given key-value pair to the dictionary.

```
func setObject(_ anObject: Any, forKey aKey: any NSCopying)
```

## Parameters

`anObject`

The value for `aKey`. A strong reference to the object is maintained by the dictionary.
  
  > Important:
  > Raises an ``doc://com.apple.foundation/documentation/Foundation/NSExceptionName/invalidArgumentException`` if `anObject` is `nil`. If you need to represent a `nil` value in the dictionary, use ``doc://com.apple.foundation/documentation/Foundation/NSNull``.

`aKey`

The key for `value`. The key is copied (using [`copy(with:)`](/documentation/Foundation/NSCopying/copy(with:)); keys must conform to the `NSCopying` protocol). If `aKey` already exists in the dictionary, `anObject` takes its place.
  
  > Important:
  > Raises an ``doc://com.apple.foundation/documentation/Foundation/NSExceptionName/invalidArgumentException`` if `aKey` is `nil`.

## See Also

[`-  removeObjectForKey:`](/documentation/Foundation/NSMutableDictionary/removeObject(forKey:))

Removes a given key and its associated value from the dictionary.

[`-  setObject:forKeyedSubscript:`](/documentation/Foundation/NSMutableDictionary/setObject:forKeyedSubscript:)

Adds a given key-value pair to the dictionary.



---

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)