Issue
I append in the for loop but for some reason instead of appending at the end it changes all the existing values in the array.
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);
}
expectd: - jack 180 ryan 120 jack 180 ryan 120
result:- jack 180 ryan 120 ryan 120 ryan 120
Solution
You create only one instance
of people
and add this instance
in your array for two times. but the problem is when you assign the value for the second time it replaces the previous value of the same instance
.
You have to create new instnse
of people
inside your for loop
for every new user. like below
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);
}
Answered By - Jakir Hossain Answer Checked By - Candace Johnson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.