Swift Insert Element At Specific Index

swift 4

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

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

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]

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

Tags:

Ios

Swift