Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Insert Element At Specific Index

Tags:

ios

swift

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 ?

like image 988
Citus Avatar asked Aug 14 '16 13:08

Citus


People also ask

How do you insert an element at a specific position in an array in Swift?

Swift Array insert() The insert() method inserts an element to the array at the specified index.

What does .append do in Swift?

Adds a new element at the end of the array.

How do you add a character to the front of a string Swift?

Swift – Insert a Character in String at Specific Index To insert a character in string at specific index in Swift, use the String method String. insert() . where str1 is the string, ch is the character and i is the index of type String. Index.


1 Answers

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]
like image 195
Damien Romito Avatar answered Sep 23 '22 08:09

Damien Romito