Glenn Von Posadas Glenn Von Posadas - 3 months ago 10
Swift Question

Swift Insert Element At Specific Index

I'm doing a project that has an online streaming of music.


  1. I have an array of object called Song - Each song in that array of Song has a URL from SoundCloud.

  2. Fast enumerate each song and then call the SoundCloud Resolve API to get the direct stream URL of each song. And store each direct url into an Array and load to my Player.



This seems to be really easy, but the #2 step is asynchronous and so each direct URL can be stored to a wrong index of array. I'm thinking to use the Insert AtIndex instead of append so I made a sample code in Playground cause all of my ideas to make the storing of direct URL retain its order, didn't work successfully.

var myArray = [String?]()

func insertElementAtIndex(element: String?, index: Int) {

if myArray.count == 0 {
for _ in 0...index {
myArray.append("")
}
}

myArray.insert(element, atIndex: index)
}

insertElementAtIndex("HELLO", index: 2)
insertElementAtIndex("WORLD", index: 5)


My idea is in this playground codes, it produces an error of course, and finally, my question would be: what's the right way to use this insert atIndex ?

Answer

This line:

if myArray.count == 0 {

only gets called once, the first time it runs. Use this to get the array length to at least the index you're trying to add:

var myArray = [String?]()

func insertElementAtIndex(element: String?, index: Int) {

    while myArray.count < index + 1 {
        myArray.append("")
    }

    myArray.insert(element, atIndex: index)
}