How to assign a dictionary link in Swift

I work with a complex dictionary and want to simplify the work by simply assigning a variable to it.

myDictionay["with"]["complex"]["sub"]["dictionary"] = "NewValue"

I just want to:

let smaller = myDictionay["with"]["complex"]["sub"]
smaller["dictionary"] = "NewValue"

How can i do this?

+4
source share
2 answers

Swift Dictionary ( Array/Set) , ( , , struct, class). , Dictionary , , , . , , , Swift Dictionary. , NSMutableDictionary, , , .

+2

:

let smaller : (inout _: [String : [String : [String :[String : String]]]], key: String, val: String) -> () = { dict, key, val in
    dict["with"]?["complex"]?["sub"]?[key] = val
    return ()
}

/* setup example */
var a = [String : String]()
var b = [String :[String : String]]()
var c = [String : [String : [String : String]]]()
var myDictionary = [String : [String : [String :[String : String]]]]()

a["dictionary"] = "OldValue"
b["sub"] = a
b["anothersub"] = a
c["complex"] = b
myDictionary["with"] = c

/* example */
print(myDictionary)
/* ["with": ["complex": ["anothersub": ["dictionary": "OldValue"],
    "sub": ["dictionary": "OldValue"]]]] */

smaller(&myDictionary, key: "dictionary", val: "NewValue")
print(myDictionary)
/* ["with": ["complex": ["anothersub": ["dictionary": "OldValue"],
    "sub": ["dictionary": "NewValue"]]]] */

, : , , (.. ).

let smaller2 : (String, String) -> () = { myDictionary["with"]?["complex"]?["sub"]?[$0] = $1 }
smaller2("dictionary", "NewerValue")
print(myDictionary)
/* ["with": ["complex": ["anothersub": ["dictionary": "OldValue"],
    "sub": ["dictionary": "NewerValue"]]]] */

myDictionary , , , , " ", . "with.complex.sub", :

/* say 'myDictionary' is some class property (initialized as in example above)
   In same class, introduce the following method */
func dictClosure(dictKeyPath: String) -> ((String, String) -> ()) {
    let arr = dictKeyPath.componentsSeparatedByString(".")
    if arr.count == 3 {
        return {
            myDictionary[arr[0]]?[arr[1]]?[arr[2]]?[$0] = $1 }
    }
    else {
        return {
            _, _ in
            print("This closure is invalid")
        }
    }
}

/* example usage */
var smaller3 = dictClosure("with.complex.sub")
smaller3("dictionary", "NewestValue")
smaller3 = dictClosure("with.complex.anothersub")
smaller3("dictionary", "AlsoNewValue")
print(myDictionary)
/* ["with": ["complex": ["anothersub": ["dictionary": "AlsoNewValue"], 
    "sub": ["dictionary": "NewestValue"]]]] */

("one.two.three") .


, , smaller - , . . smaller3("dcitionary", "NewValue") - "dcitionary": "NewValue" . , ? smaller :

/* smaller ... */
dict["with"]?["complex"]?["sub"]?[key]? = val

/* smaller2 ... */
myDictionary["with"]?["complex"]?["sub"]?[$0]? = $1

/* smaller3 ... */
myDictionary[arr[0]]?[arr[1]]?[arr[2]]?[$0]? = $1
+1

Source: https://habr.com/ru/post/1625582/


All Articles