swift add to array code example

Example 1: swift append element to array

//To add a new element to the end of an Array.
anArray.append("This String")

//To append a different Array to the end of your Array.
anArray += ["Moar", "Strings"]
anArray.append(contentsOf: ["Moar", "Strings"])

// To insert a new element into your Array.
anArray.insert("This String", at: 0)

// To insert the contents of a different Array into your Array.
anArray.insert(contentsOf: ["Moar", "Strings"], at: 0)

Example 2: how to obtain array in array in swift

import UIKit

var str = "Hello, playground"

var setOfQuestion = ["q1","q2","q3","q4","q5"]

var setOfAnswers = ["A1","A2","A3","A4","A5"]

var setOfImages = ["Img1","Img2","Img3","Img4","Img5"]

var setOfArray = [[1,2,3,4],[5,6,7,8],[9,10,11],[12,13,14],[15,16]]

var setOfArrays = [setOfQuestion,setOfAnswers,setOfImages,setOfArray] as [Any]
for n in 0...3{
    let x = n
    //Not able to get array from arry
    print(setOfArrays as [[Any]0+x][0])

}

Example 3: how to insert element at start of the array ios swift

someArray.insert(someValue, atIndex: 0)

Example 4: swift append to array

var numbers = [1, 2, 3, 4, 5]
numbers.append(100)
print(numbers)
// Prints "[1, 2, 3, 4, 5, 100]"

Example 5: add to beginning of array swift

//Swift 4
someArray.insert(someValue, at: 0)