TomSawyer TomSawyer - 4 months ago 7
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)
print(a)


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

Answer

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

Dictionary

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"]
Comments