I'm doing a project that has an online streaming of music.
I have an array of object called Song - Each song in that array of Song has a URL from SoundCloud.
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 ?
Swift Array insert() The insert() method inserts an element to the array at the specified index.
Adds a new element at the end of the array.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With