Wednesday, November 22, 2017

Swift 4 Book I Chapter 4: Swift Basic Collection Types

Chapter 4: Swift Basic Collection Types

Collection types are data type that store a collection of values instead of a single value. Swift support 3 basic collection types, they are arrays, sets and dictionaries.


  • Arrays are collection type that store its value in order.
  • Sets are collection of unique values that are unordered.
  • Dictionaries are collection that contain a key and value in a pair. Dictionaries are unordered.


If we declared an array, set or dictionary as constant, we cannot change, add or remove the items in the collection once it has been assigned. If we declare them as variables then we can change the value of the item, add item or remove item.


This chapter will cover the most commonly used collection type - the array.

Array

An array stores its value in the order that it has been assigned. We can store a value multiples times at different location.


Declared and Create An Array

Create An Empty Array

To declared an empty array, we use the syntax:
var <variable_name> = [<array_datatype>]()


Example:


var testArray1 = [String]()


testArray1






Example 2:


var testArray2 = [Int]()


testArray2




Create An Array with Literal Values

To create an array with literals we use the syntax as follows:


var <variable_name> = [<array_lierals_values_separated_by_comma>]


We have an alternative syntax, where array data type is specified


var <variable_name>: [<array_datatype>] = [<array_lierals_values_separated_by_comma>]


Example:


var testArray3 = ["a", "b", "c"]


testArray3




Example:


var testArray4 = [56, 87, 93]


testArray4




In the previous example, we can ignore the array data type since the system can infer the data type from the values.


However, if we want to be specific and avoid any ambiguity especially between integer and floating point number. We can specify the array data type as double and use integer as data values. The system will refer to the specified data type.


Example:


var testArray5: [Double] = [56, 87, 93]


testArray5




Without the specific data type, the system will infer the above array as integer array.


Create An Array with Same Default Value

We can create an array with all the items initialized with the same default value. To do so, we use the syntax as follows:


var <variable_name> = Array(repeating:<array_default_values>, count:<number_of_items>)


Example:


var testArray6 = Array(repeating: 0, count: 10)


testArray6




Example:


var testArray7 = Array(repeating: "Hi", count: 10)


testArray7




Create An Array by Adding Existing Array

We can create a new array by adding 2 existing array provided the 2 existing array has the same data type.


Example:


var existingEmployee = ["Smith", "Richards", "Carpenters", "Johnson", "Jones"]


var newEmployee = ["Willams", "Taylor"]


var newNameList = existingEmployee + newEmployee




Please note that the number next to the name is the index value in the array. For arrays, index value starts from 0 instead of 1.

Working with Array

In the following section, we will be discussing on how to work with arrays. We will discuss how to find out the total number of items in the array. We also discuss on how to access, modify and add items in the array.


Array Count

We can find out the total number of array using the property count. The access the property use the following syntax:


<array_variable_name>. count


Example:
We continue with the previous example. To count the total item in newNameList, use the following statement:


// continue from previous code
newNameList.count




Alternatively, we can also find out the total item by finding the end index. Please note that for end index, Swift return the last index used + 1.


In our example, we have 7 item and the index range from 0 to 6. So the last index is 6 + 1 which is 7 and it is equal to count.




Please note that startIndex is always equal to 0.

Empty Array

We can also check if an array is empty using the property isEmpty. The syntax is as follows:


<array_variable_name>.isEmpty


It will return a boolean value with either true or false.


Example:
We will be using the array in the previous example:


newNameList.isEmpty


var newArray = [Int]()


newArray.isEmpty




Purge Existing Array

We can reset existing array to an empty array using the follow:


<array_name> = []


Example:
This is also a continuation from previous example, please do not delete the previous example.


newEmployee


newEmployee.isEmpty


newEmployee = []


newEmployee.isEmpty




Accessing Items in Array

To retrieve an item in the array, we use index to call the particular item. The syntax is as follows:


<array_name>[<index>]


Example:
This is a continuation from previous example, please do not delete the previous example.


newNameList[0]
newNameList[1]
newNameList[2]
newNameList[6]




We can also use range index as follows:


newNameList[4...6]

newNameList[2..<6]

newNameList[0...]

newNameList[...4]

newNameList[..<6]




We can also retrieve the last item using the property .last. The syntax is as follows:


<array_name>.last


Example:


newNameList.last


Appending Items in Array

There are many ways to append items to existing array. The first method is using the method .append. The syntax is as follows:


<array_name>.append(<item_value>)


Example:


newNameList.append("Brown")


newNameList.count


newNameList.endIndex


The second method to append multiple items to an existing array use the compound assignment operator of +=. The syntax is as follows:


<array_name> += [<array_item_value_separated_by_comma>]


Example:


newNameList += ["Evans", "Thomas", "Lewis", "Robinson"]


newNameList.count




Modifying Items in Array

To modify an item, we just reassigned the item with a new value. Syntax is as follows:


<array_name>[<index>] = <new_item_value>


Example:


newNameList[1]


newNameList[1] = "Thompson"


newNameList[1]




We can also use range operator to replace a couple of items.


Example:


newNameList[3...6]


newNameList[3..<6]


newNameList[3..<6] = ["Miller", "Davis"]


newNameList[3..<6]




In the previous example, we replace item in index 3 and 4 and at the same time we remove index 5. Therefore item in index 6 will shift to become index 5.


We can also use the new one-sided range operator.


Example:


var newNameList2 = newNameList


newNameList2.count
newNameList2


newNameList2[4...] = ["Marry", "Lucy"]


newNameList2.count
newNameList2




Insert Items in Array

To insert an item in an array, we use the method .insert(_: at:). The syntax is as follows:


<array_name>.insert(<new_item>, at:<index>)


Using this method, we can choose to insert a new item at the selected index.


Example:


newNameList[3...5]


newNameList.insert("Pearson", at:3)


newNameList[3...5]




Once a new item is inserted, the remain item after the new inserted item will be push forward. The index will increase by 1.


Remove Items in Array

To remove item in an array, we use the method .remove(at:). The syntax is as follows:
<array_name>.remove(at:<index>)


Please note that the method also return the value of the remove item.


Example:


newNameList[6]


newNameList.remove(at: 6)


newNameList[6]




Once an item is removed, the index will push up. We can also capture the value of removed item as shown in the example below.


Example:


let itemRemoved = newNameList.remove(at: 1)


itemRemoved



Remove Last Item in Array



We can also use the method .removeLast() to remove the last item in an array. Similarly, the method also return the value of the removed item.


Syntax:
<array_name>.removeLast()


Example:


let lastItemRemoved = newNameList.removeLast()


lastItemRemoved



Iteration Over an Array

To run through every item in an array, we use for-in loop. The syntax is as follows:


for <item_name> in <array> {
<instruction_for_each_item>
}


Example:


for name in newNameList {
   
   print("Emplyee last name: " + name)
   
}



To include index for each array we need to add enumerated() method to the array. See example below:


for (index, name) in newNameList.enumerated() {
   
   print("Emplyee \(100 + index) last name: " + name)
   
}


*** End of Chapter ***

No comments:

Post a Comment