gpt4 book ai didi

swift - 当我 append 一个值时,整个数组都会更改为 append 值

转载 作者:行者123 更新时间:2023-11-28 13:26:18 24 4
gpt4 key购买 nike

我在 for 循环中追加,但出于某种原因,它没有在末尾追加,而是更改了数组中的所有现有值。

let a = 2

class people {
var name = " "
var height = Int()
}

var trial = " "

var p = [people]()
var user = people()
for i in 0...a-1{

if(i==0){
user.name = "jack"
user.height = 180
}
else {
user.name = "ryan"
user.height = 120
}

p.append(user)
print(p[i].name, p[i].height);

}
for i in 0...a-1 {
print(p[i].name, p[i].height);
}

预计:-千斤顶180瑞安 120千斤顶180瑞安 120

结果:-千斤顶180瑞安 120瑞安 120瑞安 120

最佳答案

您只创建一个 instancepeople 并将此 instance 添加到您的数组中两次。但问题是,当您第二次分配该值时,它会替换同一 instance 的先前值。

您必须在for 循环 中为每个新用户创建 的新instnse。如下图

let a = 2

class people {
var name = " "
var height = Int()
}

var trial = " "

var p = [people]()
//var user = people() remove this line from here and add inside for-loop
for i in 0...a-1{
var user = people() // add this line here.

if(i==0){
user.name = "jack"
user.height = 180
}
else {
user.name = "ryan"
user.height = 120
}

p.append(user)
print(p[i].name, p[i].height);

}
for i in 0...a-1 {
print(p[i].name, p[i].height);
}

关于swift - 当我 append 一个值时,整个数组都会更改为 append 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58302529/

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