在特定索引处快速插入元素

问题描述:

我正在做一个有在线音乐流的项目。在特定索引处快速插入元素

  1. 我有对象的数组称为 - 宋的该阵列中每首歌都有从SoundCloud的URL。

  2. 快速枚举每首歌曲,然后调用SoundCloud 解析API以获取每首歌曲的直接流URL。并将每个直接url存储到一个数组中并加载到我的播放器中。

这似乎很容易,但#2步是异步的,所以每个直接的URL可以存储到一个错误的数组索引。我正在考虑使用插入AtIndex而不是追加所以我在上做了一个示例代码Playground导致我的所有想法都使直接URL的存储保持其顺序,没有成功。

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) 

我的想法是在这个操场上的代码,它产生当然是一个错误,最后,我的问题是:什么是使用这个插入正确的方式atIndex

这条线:

if myArray.count == 0 { 

只被调用一次,第一次运行时。使用此得到数组的长度至少索引你想补充:

var myArray = [String?]() 

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

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

    myArray.insert(element, atIndex: index) 
} 
+0

解决了!谢谢! – Citus

+0

我会用这种方式重写整个循环: while myArray.count

,这样很容易与斯威夫特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] 
+1

当试图访问大于a.count的索引时,未能检查索引是否合法会导致“索引超出范围” - 1.在这方面@Shades的答案是优越的。 –

swift3

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

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