Array in Swift

September 27, 2017

Define empty interger array

var array = [Int]()
print("Array is empty \(array.isEmpty)")

You can us isEmpty property to check whether the array is empty

Add element to array

array += [4,5]

You can insert element at specific index

array.insert(10, at: 0)

This will add 10 at the index 0

Remove Elements

To remove element at specific location you can use remove()

array.remove(at: 1)

Remove all elemnts


You can define array with elemnts

var numbers: [Int] = [1,2,3,4,5,6,7,8,9]

Iterating Array

To loop through the array you can use for loop

for number in numbers {
    print("Number is: \(number)")

Number is: 1
Number is: 2
Number is: 3
Number is: 4
Number is: 5
Number is: 6
Number is: 7
Number is: 8
Number is: 9

You can use this for loop to loop through the array

for i in 0 ... numbers.count-1 {
    print("Number is: \(numbers[i])")

Another method

for (index,value) in numbers.enumerated(){
    print("Index is: \(index) and Value is \(value)")


Define double array with 5 elements