如何为 Swift 中的词典创建自定义扩展?
How can make a custom extension for Dictionary in Swift?
我正在尝试向 Dictionary 添加一个函数,这个函数称为 add,它有 2 个输入值(键和值)。我试图使 func 成为通用的,这意味着我希望键和值能够采用任何类型。我结束了这个不工作的代码。接下来我应该怎么做才能使这个功能发挥作用?
extension Dictionary {
func add<Key, Value>(key: Key, value: Value) {
self[Key] = Value
}
}
首先,您尝试将类型而不是实例分配给字典。
Type of expression is ambiguous without more context):
其次,您需要将您的方法声明为可变的。
Cannot assign through subscript: subscript is get-only).
第三,您正在创建两个与 Dictionary 泛型键和值类型无关的新泛型类型。
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]
我正在尝试向 Dictionary 添加一个函数,这个函数称为 add,它有 2 个输入值(键和值)。我试图使 func 成为通用的,这意味着我希望键和值能够采用任何类型。我结束了这个不工作的代码。接下来我应该怎么做才能使这个功能发挥作用?
extension Dictionary {
func add<Key, Value>(key: Key, value: Value) {
self[Key] = Value
}
}
首先,您尝试将类型而不是实例分配给字典。
Type of expression is ambiguous without more context):
其次,您需要将您的方法声明为可变的。
Cannot assign through subscript: subscript is get-only).
第三,您正在创建两个与 Dictionary 泛型键和值类型无关的新泛型类型。
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]