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

时间:2019-10-09 10:52:39

标签: swift append

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

1 个答案:

答案 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);
}

快乐编码