Andrew Schreiber Andrew Schreiber - 5 months ago 38
Swift Question

Extension on swift mutable dictionary

I'm trying to create an extension on mutable dictionaries of types


Here is the syntax for an immutable dictionary extension in Swift for

extension Dictionary where Key:NSObject, Value:AnyObject {
func addSomething() {
// Fails
self["ExampleKey"] = "ExampleValue"

However, in this case
cannot be appended to, because the extension works on immutable dictionaries. The question is what syntax is missing in order to make an extension for exclusively mutable dictionaries.

Edit: Updated to address ambiguity


By adding the
prefix to
, I can operate on only mutable dictionarys. Yay! However, the function still is not working

mutating func addSomething() {
// Error: Cannot subscript a value of type 'Dictionary<Key, Value>' with an index of type 'String'
self["ExampleKey"] = "ExampleValue"

If I cast
to a Key, I get another error:

mutating func addSomething() {
let key = "ExampleKey" as! Key
// Error: Ambiguous reference to member 'subscript'
self[key] = "ExampleValue"

Still researching how to get this simple addition to work...

Answer Source

This works

extension Dictionary where Key:NSObject, Value:AnyObject {
    mutating func addSomething(forKey key:Key, value: Value) {
        self[key] = value

var dict = [NSString:NSString]()

dict.addSomething(forKey: "test", value: "some test")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download