Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
107 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 Reply

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...