user14890475
user14890475

Reputation:

How can make a custom extension for Dictionary in Swift?

I am trying to add a function to Dictionary, this func called add, which has 2 input values (key and value). I tried to make the func be generic, that means I want key and value be able take any Type. I end it up to this down non-working code. What I should do next to make this func work?

extension Dictionary {
    func add<Key, Value>(key: Key, value: Value) {
        self[Key] = Value
    }
}

Upvotes: 0

Views: 411

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236370

First, you are trying to assign a type instead of an instance to the dictionary.

Type of expression is ambiguous without more context):


Second, you need to declare your method as mutating.

Cannot assign through subscript: subscript is get-only).


Third, you are creating two new generic types that have no relation with the Dictionary generic Key and Value types.

Cannot convert value of type 'Key' (generic parameter of instance method 'add(key:value:)') to expected argument type 'Key' (generic parameter of generic struct 'Dictionary').


extension Dictionary {
    mutating func add(key: Key, value: Value) {
        self[key] = value
    }
}

var dict: [String: Int] = [:]
dict.add(key: "One", value: 1)
dict  // ["One": 1]

Upvotes: 1

Related Questions