gpt4 book ai didi

swift - 更改数组中的属性值

转载 作者:行者123 更新时间:2023-11-30 10:43:17 24 4
gpt4 key购买 nike

当我尝试为数组属性分配新值时,出现错误:无法分配给属性:“color”是“let”常量

struct car {
let model: String
let color: String
}

var myCars :[car] = [
car(name:"model X", color: "black"),
car(name:"model Y", color: "blue"),
car(name:"roadster", color: "red"),
car(name:"model S", color: "black"),
car(name:"model 3", color: "black")
]

let colorFilter = dataSource.items.index(where: {$0.color == "black"})
myCars[colorFilter].color = "grey"

将所有颜色属性设置为“黑色”的项目替换为“灰色”

最佳答案

colorconstant (let) property ,即一次initialised你不能改变它的值。如果您想修改 color 的值,让它var而不是let

struct car {
let model: String
var color: String
}

更新color全部cars来自black to grey ,使用 map(_:) myCars数组。

myCars = myCars.map {
var newCar = $0
if newCar.color == "black" {
newCar.color = "grey"
}
return newCar
}

输出:

print(myCars)

// [car(model: "model X", color: "grey"), car(model: "model Y", color: "blue"), car(model: "roadster", color: "red"), car(model: "model S", color: "grey"), car(model: "model 3", color: "grey")]

关于swift - 更改数组中的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56338317/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com