Home > Software engineering >  Swift -Change a Struct value inside Array that is the value of a Dictionary
Swift -Change a Struct value inside Array that is the value of a Dictionary

Time:11-20

In the code below, how can I change Jack's drink from "Lemonade" to "Soda" inside the groupingDict.

struct User {
    var name: String?
    var drink: String?
}

let u1 = User(name: "Jack", drink: "Lemonade")
let u2 = User(name: "Jill", drink: "Iced Tea")

let list = [u1, u2]

var groupingDict = Dictionary(grouping: list, by: { $0.name })

print("groupingDict-original: ", groupingDict)

for (index, dict) in groupingDict.enumerated() {

    if dict.key == "Jack" {

    }
}

print("groupingDict-changed: ", groupingDict)

CodePudding user response:

Access Jack's group, go through each object using reduce(into:) and create a copy of the object and set the drink to "Soda" if it is "Lemonade"

if let jacksGroup = groupingDict["Jack"] {
    let modified = jacksGroup.reduce(into: []) {
        $0.append($1.drink == "Lemonade" ? User(name: $1.name, drink: "Soda") : $1)
    }

    groupingDict["Jack"] = modified
}
  • Related