Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Swift -Change a Struct value inside Array that is the value of a Dictionary

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)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading