TomSawyer TomSawyer - 11 months ago 43
Swift Question

Swift: How do i insert item to array with specific order?

I want to insert item at specific index in Swift. But an error has occurred:

Index is out of range

var a = [String]()
a.insert("a", atIndex: 3)
a.insert("b", atIndex: 1)
a.insert("c", atIndex: 0)
a.insert("d", atIndex: 2)

If i have to use append or insert sequentially, it will break the order i wanted.


The answer by @fiks does explain the problem and a the correct solution if you want to use Array.


Since you want to perform random insertions, using a Dictionary instead of Array does seem a more flexible choice.

var dict: [Int:String] = [:]
dict[3] = "a"
dict[1] = "b"
dict[0] = "c"
dict[2] = "d"

print(dict) // [2: "d", 3: "a", 1: "b", 0: "c"]
print(dict.sort { $0.0.0 < $0.1.0}.map { $0.1 } ) // ["c", "b", "d", "a"]