0

I have an array myarray and I am using a for loop to get a few information which I add to myarray. But next time the for-loop runs, I don't want to create a separate index, but instead the 2nd time and so on, I want to append the information to myarray[0].

How do I do that?

var myarray = [String]()

for var j in 0 < 12 {
    // do some stuff
    for var i in 0 ..< 10 {
        let parta = json?["users"][j]["name"].string
        let partb = json?["users"][j]["Lname"].string
        let partc = json?["users"][j]["dob"].string

        myarray.append("\(parta)-\(partb)-\(partc)---")
        // Here when the for loop comes back again (i = 1) , i dont want to make
        // myarray[1] ,  but instead i want myarray[0] ,
        // having value like [parta-partb-partc--parta-partb-partc]
    }
}

Basically what I am trying to do is, append the new name/lname/dob values at myarray[0] without affecting the current value/string at myarray[0].

4
  • Just assign the value at 0 index like this :- myarray[0] = json?["name"].string Commented Jul 5, 2019 at 6:36
  • 1
    Actually you are going to build a single string rather than an array. Commented Jul 5, 2019 at 6:38
  • @MandeepSingh and then how would i put Lname and dob at myarray[0] ?? I am trying to make a long string that shows name,lastname,dob of several people. (In a single string) And then put it at myarray[0] , then similarly get another very long string and put it at myarray[1](with the help of another forloop) Commented Jul 5, 2019 at 6:39
  • myarray.insert("\(parta)-\(partb)-\(partc)---", at: 0) Commented Jul 5, 2019 at 9:29

2 Answers 2

3

You can insert single element and also add array as below.

Swift 5

var myarray = [String]()
myarray.insert("NewElement", at: 0)
myarray.insert(contentsOf: ["First", "Second", "Third"], at: 0)
Sign up to request clarification or add additional context in comments.

Comments

1

If I understand your question correctly, you want to create one long string and add the new data always at the beginning of the string. One way to do that would be:

// Store somewhere
var myString = String()

for var i in(0..<10) {

    let parta = json?["name"].string
    let partb = json?["Lname"].string
    let partc = json?["dob"].string

    let newString = "\(parta)-\(partb)-\(partc)---")
    newString.append(myString)
    myString = newString
    // Here when the for loop comes back again (i = 1) , i dont want to make 
    //myarray[1] ,  but instead i want myarray[0] , 
    //having value like [parta-partb-partc--parta-partb-partc]
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.