【问题标题】:when i append a value the whole array is changing to the appended value当我附加一个值时,整个数组正在更改为附加值
【发布时间】:2020-02-06 16:41:46
【问题描述】:

我在 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 约定以大写字母开头的类命名
  • var user = people() 在 for 循环中声明
  • 你应该使用一个结构体,将它的属性声明为常量并使用它的默认初始化器struct People {let name: Stringlet height: Int}let people: [People] = [.init(name: "jack", height: 180), .init(name: "ryan", height: 120)]for person in people {print(person.name, person.height)}跨度>

标签: swift append


【解决方案1】:

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

您必须在 for loop 中为每个新用户创建新的 instnsepeople。如下所示

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-05
    • 2015-12-20
    • 2020-10-06
    • 2018-09-28
    相关资源
    最近更新 更多