我在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
答案 0 :(得分:1)
您仅创建instance
中的一个people
,并将此instance
添加到数组中两次。但是问题是当您第二次分配值时,它将替换同一instance
的先前值。
您必须在instnse
内为每个新用户创建people
中的新for loop
。像下面一样
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);
}
快乐编码