11

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 ?

3 Answers 3

41

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]
Sign up to request clarification or add additional context in comments.

2 Comments

Failing to check that the index is legitimate will result in "Index out of range" when trying to access an index that's greater than a.count - 1. In this respect @Shades answer is superior.
if array is of String type, this error occurs Cannot convert value of type 'Int' to expected argument type 'String.Index'
29

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)
}

1 Comment

I would rewrite the whole loop conditional this way: while myArray.count <= index
4

swift 4

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

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

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.