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

# setValue(_:forKey:)

Adds a given key-value pair to the dictionary.

## Declaration

```swift
func setValue(_ value: Any?, forKey key: String)
```

## Parameters

- `value`: The value for key.
- `key`: The key for value. Note that when using key-value coding, the key must be a string (see https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/KeyValueCoding/BasicPrinciples.html#//apple_ref/doc/uid/20002170).

## Discussion

Discussion This method adds value and key to the dictionary using setObject(_:forKey:), unless value is nil in which case the method instead attempts to remove key using removeObject(forKey:).

## See Also

### Related Documentation

- [value(forKey:)](foundation/nsdictionary/value(forkey:).md)

### Adding Entries to a Mutable Dictionary

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