Error: Immutable value passed on reduce function

后端 未结 3 1056
攒了一身酷
攒了一身酷 2021-01-12 04:46

I\'m trying to do the following code that transforms an array of tuples into a dictionary but I\'m receiving a compile error saying:

Immutable value

相关标签:
3条回答
  • 2021-01-12 05:22

    You can simply make the dictionary parameter mutable by preceding it with var:

    var final = array.reduce(initial) { (var dictionary, tuple) in
                                         ^^^
    

    Note however that using reduce a new dictionary is created at each iteration, making the algorithm very inefficient. You might want to consider using a traditional foreach loop

    0 讨论(0)
  • 2021-01-12 05:30

    Swift 4 has a new variant:

    var array = [("key0", "value0"), ("key1", "value1")]
    var initial = [String: String]()
    var final = array.reduce(into: initial) { dictionary, tuple in
        dictionary[tuple.0] = tuple.1
    }
    

    Which could be expressed:

    var array = [("key0", "value0"), ("key1", "value1")]
    let final: [String: String] = array.reduce(into: [:]){ $0[$1.0] = $1.1 }
    
    0 讨论(0)
  • 2021-01-12 05:31

    On Swift 3:

    var final = array.reduce(initial) { (dictionary, tuple) -> [String: String] in
        var mutableDictionary = dictionary
        //.... make changes with mutableDictionary
        return mutableDictionary
    }
    
    0 讨论(0)
提交回复
热议问题