swift: modifying arrays inside dictionaries

后端 未结 5 952
我寻月下人不归
我寻月下人不归 2020-11-30 11:16

How can I easily add elements to an array inside a dictionary? It\'s always complaining with could not find member \'append\' or could not find an overloa

5条回答
  •  鱼传尺愫
    2020-11-30 11:41

    Here is what I was telling Nate Cook, in the comments for his quality answer. This is what I consider "easily [adding] elements to an array inside a dictionary":

    dict["key"] = dict["key"]! + 4
    dict["key"] = dict["key"] ? dict["key"]! + 4 : [4]
    

    For now, we need to define the + operator ourselves.

    @infix func +(array: T[], element: T) -> T[] {
        var copy = array
        copy += element
        return copy
    }
    

    I think this version removes too much safety; maybe define it with a compound operator?

    @infix func +(array: T[]?, element: T) -> T[] {
        return array ? array! + element : [element]
    }
    
    dict["key"] = dict["key"] + 4
    

    Finally, this is the cleanest I can get it, but I'm confused about how array values/references work in this example.

    @assignment func +=(inout array: T[]?, element: T) {
        array = array + element
    }
    
    dict["key"] += 5
    

提交回复
热议问题