Andrew Schreiber Andrew Schreiber - 24 days ago 8
Swift Question

Extension on swift mutable dictionary

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

[NSObject:AnyObject]


Here is the syntax for an immutable dictionary extension in Swift for
[NSObject:AnyObject]
:

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


However, in this case
self
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

Update:

By adding the
mutating
prefix to
addSomething
, 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
"ExampleKey"
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")