我正在尝试做什么:
var
)。 在ObjC中,使用NSMutableDictionary
可以很容易地实现这一点。在Swift中,这更加棘手,因为字典被复制到局部变量中。
我认为解释我想要实现的目标的最好方法是通过代码示例:
class MyClass {
/// There are several dictionaries as instance variables
var dict1: [String : String] = [ : ]
var dict2: [String : String] = [ : ]
// ...
/// This method should change a value in one of the dictionaries,
/// depending on the argument.
func changeDictAtIndex(index: Int) {
var dict: [String : String]
if index == 0 {
dict = dict1
}else{
dict = dict2
}
dict["OK"] = "KO"
// This won't work since Swift copies the dictionary into
// the local variable, which gets destroyed at the end of
// the scope...
}
}
let obj = MyClass()
obj.changeDictAtIndex(0)
obj.dict1 // Still empty.
问题:是否有原生方式(原生意味着没有使用NSMutableDictionary
)?
P.S。:我知道inout
属性,但只使用函数参数AFAIK,它并没有真正解决任何问题......
编辑:
我目前正通过关闭来解决这个问题:
var dictSetter: (key: String, value: String) -> Void
if index == 0 {
dictSetter = { self.dict1[$0] = $1 }
}else{
dictSetter = { self.dict2[$0] = $1 }
}
dictSetter(key: "OK", value: "KO")
答案 0 :(得分:1)
您可能已经知道,可以使用inout
来解决问题
func updateDict(inout dict: [String : String]) {
dict["OK"] = "KO"
}
func changeDictAtIndex(index: Int) {
if index == 0 {
updateDict(&dict1)
}else{
updateDict(&dict2)
}
}
答案 1 :(得分:0)
Question: Is there a native way to do this (native meaning without using NSMutableDictionary)?
I have rewritten your class, note the changes:
I would look at the Apple's The Swift Programming Language (Swift 2.1)部分是一个好主意。
class MyClass {
// There are several dictionaries as instance variables
var dict1 = [String : String]()
var dict2 = [String : String]()
func changeDictAtIndex(index: Int, dict: [String : String]) {
if index == 0 {
dict1 = dict
} else {
dict2 = dict
}
}
}
用法:
let obj = MyClass()
obj.changeDictAtIndex(0, dict: ["MyKey" : "MyValue"])
print(obj.dict1)