ios Swift 在特定索引处插入元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38942905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:54:36  来源:igfitidea点击:

Swift Insert Element At Specific Index

iosswift

提问by Citus

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 APIto get the direct stream URL of each song. And store each direct url into an Array and load to my Player.

  1. 我有一个名为Song的对象数组- 该 Song 数组中的每首歌曲都有一个来自 SoundCloud 的 URL。

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

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 AtIndexinstead of appendso I made a sample code in Playgroundcause all of my ideas to make the storing of direct URL retain its order, didn't work successfully.

这看起来真的很简单,但是 #2 步骤是异步的,因此每个直接 URL 都可以存储到错误的数组索引中。我正在考虑使用Insert AtIndex而不是append所以我在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)

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?

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

回答by Damien Romito

Very easy now with Swift 3:

现在使用 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]

回答by Shades

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

回答by Deepak Tagadiya

swift 4

迅捷 4

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

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