我在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
您必须在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
}