15. Arrays in Swift

In Swift you can declare variables with keyword var and the constants with keyword let.

var name = "Khan";
let pie = 3.141

If you want to keep all these variables or constants in one place so you can access them one by one, here comes a solution, a powerful data structure called Array. Array is designed to keep multiple values in one order so you can access them one by one.

Array Declaration

Declaration of array is same as variable or constant with one exception, [ ] brackets. You can declare array as mentioned bellow:

var name_of_array = [value1, value2,....]
var priceList = [12, 45]

let name_of_array = [value1, value2,....]
let daysOfWeek = ["Saturday","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday"]

Type of the array depends on value which you will assign to this array. priceList  is integer type of array and daysOfWeek is array of strings.

Swift provides functionalities to declare specific type of array. The syntax is as follow:

var name_of_array: [type] = [values]
var myInteger: [Int] = [10]

One thing is very important to notice, once the array type is defined it is not possible to add value other than array type. In these previous examples, myInteger is Integer type of array. Swift will immediately throw an error if you will try to assign string or float.

 Access value in array

Array always stores data in sequence and that sequence starts from zero.

var priceList = [12, 45, 68, 90]

Access first element of the array,

priceList[0]

for second element

priceList[1]

 

Swift provides a wide range of methods for working with Array and its contents.

Array Count
You can obtain the array count by using function called count.

var arraycount = priceList.count
println(arraycount)

 

Is Array Empty
Array is empty or not, try isEmpty method. It will return boolean value true if empty otherwise false

priceList.isEmpty

 

Insert more items in array
Items can be added to the array by different ways. Use Swift provided method “append”, this method will insert value at the end of array.

// By using append method 
priceList.append(90)

+= operator is also a good alternative of append method

// By using += operator
priceList += [110]

A new item can be inserted at specific index of the array by using “insert” method

// insert at specific location
priceList.insert (yours_value, index_number)
priceList.insert(100, atIndex: 3)

 

Update array items
You can replace any item of the array by using index number.

priceList[2] = 120

If the size of your array is 5 and you want to replace the value of index 9, Swift will immediately throw an error of boundary limit.

priceList[9] = 120

 

Delete array items
You can remove array items by different ways. A specific item can be removed or you can remove last item of the array.

priceList.removeAtIndex(0)

priceList.removeLast

 

removeAll with capacity
You can also remove all elements of the array by using removeAll method. To explain this method, lets create a new array.

var colors = ["RED","GREEN","BLUE","YELLOW"]

Try count method and you will get 4 in answer

colors.count

Now try a method called capacity, this method will also return 4. Because colors array is initialized with 4 values.

colors.capacity

now use a method called ‘removeLast’ and try ‘count’ and ‘capacity’ method one more time.

colors.removeLast

colors.count
colors.capacity

count method will return 3 and capacity method will still return 4. Which shows that one item is removed from array but array itself has a capacity to have 4 items. Now see how removeAll method works.

If colors array contains 4 items, removeAll method will remove all 4 items and “count” method will return 0.

colors.removeAll(keepCapacity: true)

Notice that removeAll method takes one parameter: keepCapacity, it can be true or false. If you will pass the value “true”, array “colors” will keep the capacity to handle 4 items. If you will assign false to keepCapacity, both count and capacity will become 0.

Sort array 
You can sort an array by using sorted “method”. Pass {$0 < $1} for ascending order and {$1 < $0} for descending order. 

let sortedcolors = colors.sorted() {$0 < $1}

Notice that sorted method does not change original array but it returns the sorted array which you can keep in constant or in variable. In this  case “sortedcolors” contains sorted array and “colors” array is still in its original form

 

Access all element of the array
Best way to access all elements of the array is for loop

for price in priceList{
    println(price)   
}

 

 

Download file from GitHub