本地Swift词典参考

时间:2015-12-15 00:55:26

标签: swift dictionary

我正在尝试做什么:

  • 一个类,它有几个(比方说10个)字典类型的实例变量(mutable 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")

2 个答案:

答案 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:

  • Different syntax for empty dictionary
  • ChangeDictAtIndex function now takes in a dictionary you want to replace.
  • The instance variables are being set to the passed in dict.

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)