Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
104 views
in Technique[技术] by (71.8m points)

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
    }
}
question from:https://stackoverflow.com/questions/65545846/how-can-make-a-custom-extension-for-dictionary-in-swift

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...