PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, May 13, 2022

[FIXED] when i append a value the whole array is changing to the appended value

 May 13, 2022     append, swift     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing