Swift -更改数组中的结构值,该值是字典的值

xpcnnkqh  于 2022-11-21  发布在  Swift
关注(0)|答案(2)|浏览(155)

在下面的代码中,如何在groupingDict中将Jack的饮料从“Lemonade”更改为“Soda”。

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)
368yc8dk

368yc8dk1#

访问Jack的组,使用reduce(into:)遍历每个对象,并创建对象的副本,如果饮料为“Lemonade”,则将其设置为“Soda”

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
}
qxsslcnc

qxsslcnc2#

我找到了另一种方法。你可以使用firstIndex(where: { }来获取条目的索引,修改属性,创建一个条目的副本,然后赋给字典值:

for (_, dict) in groupingDict.enumerated() {
    
    if dict.key == "Jack" {

        if var arr = groupingDict["Jack"] {

            if let indexOfItem = arr.firstIndex(where: { $0.name == "Jack" }) {

                arr[indexOfItem].drink = "Soda"
                
                let copyOfItem = arr[indexOfItem]
                
                groupingDict["Jack"] = [copyOfItem]
            }
        }
    }
}

相关问题