---
title: "setObject(_:forKey:)"
framework: foundation
role: symbol
role_heading: Instance Method
path: "foundation/nsmutabledictionary/setobject(_:forkey:)"
---

# setObject(_:forKey:)

Adds a given key-value pair to the dictionary.

## Declaration

```swift
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 doc://com.apple.foundation/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

### Related Documentation

- [removeObject(forKey:)](foundation/nsmutabledictionary/removeobject(forkey:).md)

### Adding Entries to a Mutable Dictionary

- [setValue(_:forKey:)](foundation/nsmutabledictionary/setvalue(_:forkey:).md)
- [addEntries(from:)](foundation/nsmutabledictionary/addentries(from:).md)
- [setDictionary(_:)](foundation/nsmutabledictionary/setdictionary(_:).md)
