【发布时间】:2018-12-10 11:28:59
【问题描述】:
我正在编写一个 Swift 类,它在实例化它时构建一个字典,加上添加键值对的可能性,但是一旦完成,问题是我无法访问我添加的各个对,所以肯定有问题我无法检测到的地方,请帮助
class MyDictionary {
var dictionary = ["":""]
init() {
}
func addPair(key: String, value: String) {
//dictionary["key"] = "value"
dictionary.updateValue(value, forKey: key)
}
}
// just to compare... this one works
var dict = ["one": "abc"]
dict["two"] = "efg"
print(dict["two"]!)
let myDictionary = MyDictionary()
myDictionary.addPair(key: "key1", value: "value1")
print(myDictionary)
//print(myDictionary["key1"]) //Does not work
【问题讨论】:
-
dictionary["key"] = "value" 这会起作用。
-
它不应该工作,因为 myDictionary 是 Class 类型而不仅仅是 Swift Dictionary