当我附加一个值时,整个数组都将更改为附加值

问题描述 投票:0回答:1

我在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

swift append
1个回答
1
投票

您必须在user中创建for loop。像这样

for i in 0...a-1{
var user = people()
if(i==0){
    user.name =  "jack"
    user.height = 180
}
else{
    user.name =  "ryan"
    user.height = 120
}
© www.soinside.com 2019 - 2024. All rights reserved.