简体   繁体   中英

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 ?

Very easy now with Swift 3:

// Initialize the Array
var a = [1,2,3]

// Insert value '6' at index '2'
a.insert(6, atIndex:2)

print(a) //[1,2,6,3]

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 {
        myArray.append("")
    }

    myArray.insert(element, atIndex: index)
}

swift 4

func addObject(){
   var arrayName:[String] = ["Name0", "Name1", "Name3"]
   arrayName.insert("Name2", at: 2)
   print("---> ",arrayName)
}

Output: 
---> ["Name0","Name1", "Name2", "Name3"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM