Swift 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.
For safer coding, we are recommended to use constant if the element in the collection will not be changed or modified.
Arrays, sets, dictionaries and string belongs to collection types. String is a collection of character arrays. Therefore, there are some methods and properties that are common between these collection types. These collection types are implemented as generics collection.
Array
An array stores its value in the order that it has been assigned. We can store same 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 <array_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>]
Please note that the system can infer integer, double, string and boolean. For other data type including optionals, we need to specify the data type. Therefore, we need to use the second syntax.
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 specified data type, the system will infer the above array as integer array.
For other data type that the system could not infer, we need to specify them as shown below:
var testArray6:[UInt] = [1299675, 2334534,645645]
testArray6 |
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 that 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.
Array Basics
We will be using the following 2 arrays for all the examples in this chapter. In the event that any of the array is mess up or lost. Please use the snippet below to re-create the array:
var existingEmployee = ["Smith", "Richards", "Carpenters", "Johnson", "Jones"]
var newEmployee = ["Willams", "Taylor"] var newNameList = existingEmployee + newEmployee var numberList = [12,34,54,67,43,89,23,38,72] |
Access Entire Array
To access the entire array, we can use the array name as shown in the example below:
newNameList
print(newNameList) |
Another example using number array:
numberList
print(numberList) |
Access Array Item
To retrieve an item in the array, we use index to call the particular item. Please note that the order of the array is based on how we add the items, with the last item added at the bottom of the list. The index of the array starts from 0 instead of 1. This also means that if we have 8 items in the array, the last item in the index will be 7 instead of 8.
To access an item use the syntax below:
<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] |
numberList[0]
numberList[1] numberList[2] numberList[6] |
Array Count
We can find out the total number of array using the property count. To 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
newNameList.count
newNameList.endIndex
newNameList.startIndex
|
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.
The other array example:
numberList
numberList.count numberList.endIndex numberList.startIndex |
Please note that for empty array, the startIndex is the same as endIndex.
let empty = [String]()
empty.startIndex == empty.endIndex empty.isEmpty |
Example from number array:
let emptyNumber = [Int]()
emptyNumber.startIndex == emptyNumber.endIndex emptyNumber.isEmpty |
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 |
Accessing and Extracting Array Item
Access First and Last Item
We can also retrieve the first item using the property .first. The syntax is as follows:
<array_name>.first
Please note that the above is a variable/property from the array.
Example:
newNameList.first
numberList.first |
We can also retrieve the last item using the property .last. The syntax is as follows:
<array_name>.last
Please note that the above is a variable/property from the array.
Example:
newNameList.last
numberList.last |
Maximum and Minimum Value
We can also find the maximum and minimum value using the methods .max() and .min(). The syntax for finding the maximum value item in an array is as follows:
<array_name>.max()
Please note that the above function will return a single array item.
Example:
let maxName = newNameList.max()
let maxNumber = numberList.max() |
The syntax for finding the minimum value item in an array is as follows:
<array_name>.min()
Please note that the above function will return a single array item.
Example:
let minName = newNameList.min()
let minNumber = numberList.min() |
Why "Willams" is consider maximum in value and "Carpenters" is the minimum in value. If we consider the first letter W and C, we can defer that for string item, the system will find the Unicode value of the first letter. Thus in this case W has the largest value and C has the smallest value. The max and min method is straight forward for arrays of integer. It will return the largest and smallest number.
|
Using Prefix and Suffix Method
What happen if we want to extract the first few or last few item? We can use prefix or suffix method. The prefix method extract a number of item from the beginning of the array. The suffix method extract a certain number of item starting from the end of array.
Prefix Method
There are 3 ways of using prefix method. These ways are illustrated below:
- <array>.prefix(<no_of_item_to_extract>) - This method allow us to extract user define number of item from the beginning of array.
- <array>.prefix(through:<array_index>) - This method allow us to extract array item from the beginning of array up to and including the array index indicated by us.
- <array>.prefix(upTo:<array_index>) - This method allow us to extract item from the beginning of array up to the indicated array index but excluding the array index.
Please also note that the methods above only extract the items and return us a portion of array known as array slice. The array itself is not affected.
Example:
// Extract first 3 item
let firstThree = newNameList.prefix(3) // Extract the first 4 item let firstFour = newNameList.prefix(4) // Extract from begining until and include index 4 let includingIndex4 = newNameList.prefix(through: 4) // Extract from begining up to but exclude index 4 let upTo3 = newNameList.prefix(upTo: 4) // No change to the original array newNameList |
The number array example:
// Extract first 3 item
let firstThreeNumber = numberList.prefix(3) // Extract the first 4 item let firstFourNumber = numberList.prefix(4) // Extract from begining until and include index 4 let includingIndex4Number = numberList.prefix(through: 4) // Extract from begining up to but exclude index 4 let upTo3Number = numberList.prefix(upTo: 4) // No change to the original array numberList |
Suffix Method
There are 2 ways of using suffix method. These ways are illustrated below:
- <array>.suffix(<no_of_item_to_extract>) - This method allow us to extract user define number of item from the end of array.
- <array>.suffix(from:<array_index>) - This method allow us to extract array item from the indicated index (indicated index included) until the end of array.
Please also note that the methods above only extract the items and return us a portion of array known as array slice. The array itself is not affected.
Example:
// Extract last 2 item
let lastTwo = newNameList.suffix(2) // Extract from index 3 until end of array let fromIndex3ToEnd = newNameList.suffix(from: 3) // No change to the original newNameList |
Integer array example:
// Extract last 2 item
let lastTwoNumber = numberList.suffix(2) // Extract from index 3 until end of array let fromIndex3ToEnd = numberList.suffix(from: 3) // No change to the original numberList |
Use Drop Method
We can use drop method to extract a large portion of array by discarding the first or last few items. Please note that when we use the drop method, no changes will be affected on the array. Instead a collection of array item known as array slice will be return.
To extract all the array item except the first item using dropFirst method:
let exceptFirst = newNameList.dropFirst()
newNameList exceptFirst |
The other example:
let exceptFirstNumber = numberList.dropFirst()
numberList exceptFirstNumber |
We can all drop n item by indicating the number of item to drop in the dropFirst argument. See example below:
let exceptFirstTwo = newNameList.dropFirst(2)
newNameList exceptFirstTwo |
Example 2:
let exceptFirstTwoNumber = numberList.dropFirst(2)
numberList exceptFirstTwoNumber |
To extract all item except the last item see example below:
let exceptLast = newNameList.dropLast()
newNameList exceptLast |
Example 2:
let exceptLastNumber = numberList.dropLast()
numberList exceptLastNumber |
We can drop more than 1 item using drop last method. Let's say we want an extract of the array exclude last 3 item. We use the method below:
let exceptLastThree = newNameList.dropLast(3)
newNameList exceptLastThree |
Example 2:
let exceptLastThreeNumber = numberList.dropLast(3)
numberList exceptLastThreeNumber |
Using Index in Array
As mentioned in the previously, the index of arrays are numbered from 0. So the first item is always 0 and the last item is always the array count less 1.
Here is a few pointers to note:
- Use count property to find the total number of array.
- Indexes are numbered from 0. The last item will be count - 1.
- Use isEmpty to check is there is any item in the array.
In an array, there are a lot of functionality we can use to reference index, listed below are some of the common usage.
Index Range
Beside using index to access the array item, we can also use range index as follows:
// retrieve from item 5 to item 7
newNameList[4...6]
// retrieve from item 3 to item 6
newNameList[2..<6]
// retrieve from item 0 to the end of array
newNameList[0...]
// retrieve from beginning of array to item 5
newNameList[...4]
// retrieve from beginning of array to item 6
newNameList[..<6] |
Example 2:
numberList
// retrieve from item 5 to item 7 numberList[4...6] // retrieve from item 3 to item 6 numberList[2..<6] // retrieve from item 3 to the end of array numberList[3...] // retrieve from beginning of array to item 5 numberList[...4] // retrieve from beginning of array to item 6 numberList[..<6] |
Start Index and End Index
Instead of using 0, we can also use the property, startIndex, to reference the beginning of index:
newNameList
newNameList.startIndex |
Example 2:
numberList
numberList.startIndex |
The property endIndex will not reference the last item in the array. Instead endIndex refers to last item + 1 in an array. In another way, endIndex is also the same as count.
newNameList
newNameList.endIndex newNameList.count |
Example 2:
numberList
numberList.endIndex numberList.count |
Getting Index of Search Item
We use index(of:) to find and match an item in the array. The return result is the index of the found item. Using the example above. We can try to find 2 names one of them is in the array and the other is not. If not found, the function will return nil. Therefore the return result is an optional.
The syntax is as follows:
The syntax is as follows: let/var <index_of_searched_item> = <array>.index(of: <search_term>)
The syntax is as follows:
The syntax is as follows: let/var <index_of_searched_item> = <array>.index(of: <search_term>)
newNameList
let foundIndex = newNameList.index(of: "Johnson") let foundIndex2 = newNameList.index(of: "noName") foundIndex2 foundIndex |
Example 2:
numberList
let foundNumberIndex = numberList.index(of: 54) let foundNumberIndex2 = numberList.index(of: 77) foundNumberIndex foundNumberIndex2 |
What happen if there is similar item in the array? Let's find out
let experimentNameList2 = newNameList + ["Richards"]
experimentNameList2 let indexRichards = experimentNameList2.index(of: "Richards") indexRichards |
Example 2:
let experimentNumberList2 = numberList + [23, 45]
experimentNumberList2 let indexOf23 = experimentNumberList2.index(of: 23) indexOf23 |
As we can see from the 2 examples above, the function will return the first index of the search item. Any duplicate item will be ignore.
If there are more than one same item in an array. Index(:of) will return the first item in the array.
|
Reference Index After and Before
We can use index(after) or index(before) to find the index before or after our specified index.
The syntax is as follows: let/var <index> = <array>.index(after: <ref_index>) let/var <index> = <array>.index(before: <ref_index>)
Example:
The syntax is as follows: let/var <index> = <array>.index(after: <ref_index>) let/var <index> = <array>.index(before: <ref_index>)
Example:
newNameList.index(after: newNameList.startIndex)
newNameList.index(before: newNameList.endIndex) newNameList.index(after: 2) newNameList.index(before: 5) |
Example 2:
numberList.index(after: numberList.startIndex)
numberList.index(before: numberList.endIndex) numberList.index(after: 2) numberList.index(before: 5) |
Note: Of course it is pointless to use the above function if we know the index number in advance. We should access the item directly. However, we can use the above method when we do not know the exact index number. For example, we may have a searched index known as indexFound. We can access the previous record as arrayName.Index(before: indexFound).
We will illustrate such example below:
newNameList
let foundIndex = newNameList.index(of: "Johnson") print("The name before Johnson is \(newNameList[newNameList.index(before: foundIndex!)]).") |
In the next example, we want to display the number after the maximum number:
numberList
let foundMaxIndex = numberList.index(of: numberList.max()!) print("The number after the maximum number \(numberList.max()!) is \(numberList[numberList.index(after: foundMaxIndex!)]).") |
Reference Index with Offset
We can also reference index using offset. We use the method Index(:offsetBy:) to find the index before or after our reference.
The syntax is as follows:
let/var <index> = <array>.index(<ref_index>, offset: <offset>)
Example:
let indexRic = newNameList.index(of: "Richards")
let index4AfterRic = newNameList.index(indexRic!, offsetBy: 4) newNameList[index4AfterRic] |
If we set offset that are out of array's range the system will return error.
The other example shows that we can move backward by using negative offset:
numberList
let index67 = numberList.index(of: 67) let index2Before67 = numberList.index(index67!, offsetBy: -2) numberList[index2Before67] |
Similarly, the system will produce error when it is out of range.
To mitigate the problem mentioned above, we use index(:offsetBy:limitedBy:) to impose limit so that the index will return nil if it is out of bound.
The syntax is as follows: let/var <index> = <array>.index(<ref_index>, offset: <offset>, limitedBy: <limit>) Example:
The syntax is as follows: let/var <index> = <array>.index(<ref_index>, offset: <offset>, limitedBy: <limit>) Example:
let indexRic = newNameList.index(of: "Richards")
let index5AfterRic = newNameList.index(indexRic!, offsetBy: 5, limitedBy: newNameList.endIndex) newNameList[index5AfterRic!] let indexOutRic = newNameList.index(indexRic!, offsetBy: 10, limitedBy: newNameList.endIndex) indexOutRic if indexOutRic != nil { newNameList[indexOutRic!] } else { print("not found") } |
Example 2:
let index43 = numberList.index(of: 43)
let index3Before67 = numberList.index(index43!, offsetBy: -3, limitedBy: numberList.startIndex) numberList[index3Before67!] let indexOutRange = numberList.index(index43!, offsetBy: -10, limitedBy: numberList.startIndex) indexOutRange if indexOutRange != nil { numberList[indexOutRange!] } else { print("not found") } |
Distance
We can find out the distance of index difference between 2 indexes using the method distance(from:to:).
Syntax is as follows: let/var <index_distance> = array.distance(from: <start_index>, to: <end_index>) Example:
Syntax is as follows: let/var <index_distance> = array.distance(from: <start_index>, to: <end_index>) Example:
newNameList
// to find the distance between Carpenters and second last item let indexCarpenters = newNameList.index(of: "Carpenters") let secondLastIndex = newNameList.index(before: newNameList.endIndex) let distanceCount = newNameList.distance(from: indexCarpenters!, to: secondLastIndex) |
Example 2:
numberList
// to find the distance between 34 and second last item let index34 = numberList.index(of: 34) let secondLastIndex = numberList.index(before: numberList.endIndex) let distanceCount = numberList.distance(from: index34!, to: secondLastIndex) |
The distance between startIndex and endIndex is the total count.
newNameList
let distanceCount = newNameList.distance(from: newNameList.startIndex, to: newNameList.endIndex) newNameList.count |
Example 2:
numberList
let distanceCount = numberList.distance(from: numberList.startIndex, to: numberList.endIndex) numberList.count |
Using Range as Variable
Instead of keeping the start and end index we want, we can register the range as an variable as follows:
newNameList
// to find the distance between Carpenters and second last item let indexCarpenters = newNameList.index(of: "Carpenters") let secondLastIndex = newNameList.index(newNameList.endIndex, offsetBy: -2, limitedBy: newNameList.startIndex) let myRange = indexCarpenters!...secondLastIndex! // display item from a specific range newNameList[myRange] |
Example 2:
numberList
// to find the distance between 54 and 38 let index54 = numberList.index(of: 54) let index38 = numberList.index(of: 38) let myNumberRange = index54!...index38! // display item from 54 to 38 numberList[myNumberRange] |
Iteration Over an Array
Using For-In Loop
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)
}
Example 2:
for number in numberList {
print("The numbers in the array: \(number)")
}
for name in newNameList {
print("Emplyee last name: " + name) } |
for number in numberList {
print("The numbers in the array: \(number)") } |
Using Enumerated
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("Employee \(index) last name: \(name)")
}
Example 2:
for (index, name) in numberList.enumerated() {
print("The number index \(index) in the array is: \(name)")
}
Please note that under enumerated method, the first element is always index and the second element is always the array item regardless of the name used,
for (index, name) in newNameList.enumerated() {
print("Employee \(index) last name: \(name)") } |
for (index, name) in numberList.enumerated() {
print("The number index \(index) in the array is: \(name)") } |
Using Indices
Alternatively, we can use indices just to iterative the indices:
for index in newNameList.indices {
print("Index \(index): Name is \(newNameList[index])")
}
Example 2:
for index in numberList.indices {
print("Index \(index): Number is \(numberList[index])")
}
for index in newNameList.indices {
print("Index \(index): Name is \(newNameList[index])") } |
for index in numberList.indices {
print("Index \(index): Number is \(numberList[index])") } |
Reversing Order
We can reverse the order of the array using reversed() function. The reverse function applies to all the looping method above.
for name in newNameList.reversed() {
print("Emplyee last name: " + name)
}
Number example:
for number in numberList.reversed() {
print("The numbers in the array: \(number)")
}
Using enumerated with reverse:
for (index, name) in newNameList.enumerated().reversed() {
print("Employee \(index) last name: \(name)")
}
Please note that enumerated().reversed() is different from reversed().enumerated(). The first method is to enumerate the list and reversed the order. The second method is to reverse the list first and enumerate the list. See example below:
for (index, name) in newNameList.reversed().enumerated() {
print("Employee \(index) last name: \(name)")
}
Both list are in reverse but the index is different. Regardless of with method is deployed, the order of the original array remain intact. Similar effect on the number list.
for (index, name) in numberList.enumerated().reversed() {
print("The number index \(index) in the array is: \(name)")
}
for (index, name) in numberList.reversed().enumerated() {
print("The number index \(index) in the array is: \(name)")
}
Using indices, we can also reverse the order as shown below:
for index in newNameList.indices.reversed() {
print("Index \(index): Name is \(newNameList[index])")
}
for index in numberList.indices.reversed() {
print("Index \(index): Number is \(numberList[index])")
}
For completeness, There is also a forEach() method to iterate the array. We will discuss this when dealing with closure.
Summary:
-
To iterate each item in array use the basic for-in loop
-
To iterate only the index, use for-in loop with arrayName.indices
-
To iterate both index and item, use for-in loop with arrayName.enumerated(). The first element is always array index and second element is always the array item regardless of name used.
for name in newNameList.reversed() {
print("Emplyee last name: " + name) } |
for number in numberList.reversed() {
print("The numbers in the array: \(number)") } |
for (index, name) in newNameList.enumerated().reversed() {
print("Employee \(index) last name: \(name)") } |
for (index, name) in newNameList.reversed().enumerated() {
print("Employee \(index) last name: \(name)") } |
for (index, name) in numberList.enumerated().reversed() {
print("The number index \(index) in the array is: \(name)") } |
for (index, name) in numberList.reversed().enumerated() {
print("The number index \(index) in the array is: \(name)") } |
for index in newNameList.indices.reversed() {
print("Index \(index): Name is \(newNameList[index])") } |
for index in numberList.indices.reversed() {
print("Index \(index): Number is \(numberList[index])") } |
Summary:
|
Adding Items to Array
There are few ways to add items or append the array. We can use plus signs or plus compound assignment method to add items. We can also use append and insert method. Append method allow us to append new items at the end of array. Insert method allow us to insert an item in the middle of array.
Please note that we still use the same example without preserving additional items. The examples remain the same:
var numberList = [12,34,54,67,43,89,23,38,72]
var newNameList = ["Smith", "Richards", "Carpenters", "Johnson", "Jones", "Willams", "Taylor"] |
Joining Array with Plus Sign
We can create a new array by joining the existing array with another array using the plus sign. See example below:
var anotherNewNameList = newNameList + ["Henry" , "Lee"]
var anotherNumberList = numberList + [88, 64, 96] |
We can also join existing array with another array using plus sign:
newNameList = newNameList + ["Hammer", "Wilson", "Goldman", "Lee"]
numberList = numberList + [88, 96] |
Compound Assignment
The second method to append multiple items to an existing array use the compound assignment operator +=. The syntax is as follows:
<array_name> += [<array_item_value_separated_by_comma>]
Example:
newNameList += ["Evans", "Thomas", "Lewis", "Robinson"]
newNameList.count |
Example 2:
numberList += [13,15,17,21]
numberList.count |
Appending Items in Array
We can use the method append if we are going to append a single item. The syntax is as follows:
<array_name>.append(<item_value>)
Example:
newNameList.append("Brown")
newNameList.count newNameList.endIndex |
Example 2:
numberList.append(88)
numberList.count numberList.endIndex |
Of course Swift also provide another method that enable us to append another array instead of single item. The syntax is as follows:
<array_name>.append(contentsOf:<group_of_item _or_another_array>)
Example:
newNameList.endIndex
newNameList.append(contentsOf: ["Brown","Gibson"]) newNameList.count |
Example 2:
numberList.endIndex
let newAddArray = [17,81] numberList.append(contentsOf: newAddArray) numberList.count |
Insert Items in Array
To insert an item in the middle of 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[4] newNameList.insert("Pearson", at:4) newNameList[3...5] newNameList[4] newNameList.index(of: "Jones") |
Once a new item is inserted, the remaining item after the new inserted item will be push forward. The index will increase by 1.
Example 2:
numberList[3...5]
numberList[4] numberList.insert(77, at:4) numberList[3...5] numberList[4] numberList.index(of: 43) |
To insert more than one item, we can use the method insert(contentOf:). The syntax is as follows:
<array_name>.insert(contentsOf:<collection_of_items>, at:<index>)
We can insert more than 2 items or we can insert another array into the main array.
Example:
newNameList
newNameList.insert(contentsOf: ["Mary","Mark","Anthony"], at: 3) newNameList |
Example 2:
numberList
let anotherSubArray = [123,423,345] numberList.insert(contentsOf: anotherSubArray, at: 5) numberList |
Modifying Items in Array
Modify Single Item
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] |
Example 2:
numberList[1]
numberList[1] = 33 numberList[1] |
Modify a Range of Item
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.
Example 2:
numberList[3...6]
numberList[3..<6] numberList[3..<6] = [107,181] numberList[3..<6] |
We can also use the new one-sided range operator.
Example:
var newNameList2 = newNameList
newNameList2.count newNameList2 // replace from 3rd item to the end with Marry and Lucy newNameList2[2...] = ["Marry", "Lucy"] newNameList2.count newNameList2 |
In the previous example, we replace the item from index 2 (third item) to the end of array with 2 item. The system will remove all item from index 2 to the end of array and at the same time replace the 3rd and 4th item with the replacement item we supplied.
Example 2:
var numberList2 = numberList
numberList2.count numberList2 // replace first 5 item index 0 to 4 with 3 and 6 numberList2[...4] = [3, 6] numberList2.count numberList2 |
Modifying Using Replace Subrange
We can also modify a range of item a collection of replacement item using the method replaceSubrange(). The syntax is as follows:
<array>.replaceSubrange(<range>, with: <replacement_array>)
Example:
In the following example, we attempt to replace last 4 item of the array with the replacement.
// Replace last 4 item of array with Robins and Parks
newNameList newNameList.replaceSubrange(newNameList.index(newNameList.endIndex, offsetBy: -4)...newNameList.index(before: newNameList.endIndex), with: ["Robins","Parks"]) newNameList |
Example 2:
// Replace 43...23 with replacement array
numberList let replacementArrayNumber = [124,654,656,799] let rangeToReplace = numberList.index(numberList.startIndex, offsetBy: 4)...numberList.index(numberList.startIndex, offsetBy: 6) numberList.replaceSubrange(rangeToReplace, with: replacementArrayNumber) numberList |
Sorting Array
We can also sort an array in order using the sort method. The syntax is as follows:
<array>.sort()
Please note that once the method is executed, the order of the item will changed. The sort method works on the array that is being called. There is no way to reverse back the action. The sort function will have no return value. Alternatively, we might assigned the sorted array into another variable. To do that, we have assigned the original array to alternative variable first before sort method is called.
Example:
newNameList
newNameList[0] newNameList[1] newNameList.sort() newNameList newNameList[0] newNameList[1] |
Example 2:
numberList
numberList[0] numberList[1] var sortedNumberList = numberList sortedNumberList.sort() // The following method will not work // the original numberList will still be sorted and there is no return // let sortedNumberList = numberList.sort() sortedNumberList sortedNumberList[0] sortedNumberList[1] numberList numberList[0] numberList[1] |
To sort in descend order, we use the method sort(by:) and we use > sign for descending order.
Example:
var newNameList = ["Smith", "Richards", "Carpenters", "Johnson", "Jones", "Willams", "Taylor"]
newNameList var descendingNameList = newNameList descendingNameList.sort(by: >) descendingNameList descendingNameList[0] newNameList newNameList[0] |
Example 2:
numberList
var sortedDescendingNumberList = numberList sortedDescendingNumberList.sort(by: >) sortedDescendingNumberList sortedDescendingNumberList[0] sortedDescendingNumberList[1] numberList numberList[0] numberList[1] |
If all we want is to get the return of the sorted array, we can use the method sorted instead of sort.
Example:
newNameList
let sortedNameList = newNameList.sorted() newNameList sortedNameList |
Example 2:
numberList
let sortedNumberList = numberList.sorted() numberList sortedNumberList |
Using sorted in descending mode is as follows:
Example:
newNameList
let sortedDescendNameList = newNameList.sorted(by: >) newNameList sortedDescendNameList |
Example 2:
numberList
let sortedDescendNumberList = numberList.sorted(by: >) numberList sortedDescendNumberList |
Reverse Item in Array
We can also reverse the order of an array. To reverse the order of an array, we use the method reverse. The syntax is as follow:
<array>.reverse()
Similar to the sort method, this method also works on the array and any changes is permanent.
Example:
newNameList
newNameList.reverse() newNameList |
Example 2:
numberList
numberList.reverse() numberList |
If we want to reverse the array without touching the original array, we can use the method reversed instead of reverse. The syntax is as follows:
let <temporary_placeholder> = <array>.reversed()
Example:
newNameList
let reversedNameList = newNameList.reversed() newNameList reversedNameList for name in reversedNameList { print(name) } |
Please note that the return is a temporary reversed array. We can only iterate through the array. If we want to convert to an actual array, we need to use Array() to convert the reversed collection to an array. See the next example for illustration:
numberList
let reversedNumberList = numberList.reversed() numberList reversedNumberList let actualReverseNumberList = Array(reversedNumberList) actualReverseNumberList |
Comparing and Finding Array
We can compare 2 array using the comparison operator. Two array is the same when all the elements and its order is the same.
Example:
let anotherNewList = newNameList
newNameList == anotherNewList newNameList.sort() newNameList == anotherNewList |
As we can see from the example above, even if the element is the same, once the order is different from another array, it will be considered as different array. However, if we were to compare element by element, we can see that the element is the same.
Example 2:
var tempList = numberList
tempList == numberList tempList.sort(by: >) numberList == tempList numberList[numberList.index(of: 38)!] == tempList[tempList.index(of: 38)!] |
Finding Array Item using Contains
To find if an item is in the array, we use the method contains to find if an item is in the array.
The syntax is a s follows:
let <answer> = <array>.contains()
The method will return a true or false answer.
Example :
newNameList
let isJonesIn = newNameList.contains("Jones") if isJonesIn == true { let indexOfJones = newNameList.index(of: "Jones") print(newNameList[indexOfJones!]) } else { print("Not Found") } |
Example 2:
In the following example, we also know that if there are more than one same item, the system will return true. The index of method will only return the first index of the searched item. To get the index of second same item, we can reversed the array.
numberList
numberList.insert(89, at: 2) let is89There = numberList.contains(89) let index89 = numberList.index(of: 89) let reversedArray = Array(numberList.reversed()) reversedArray.index(of: 89) |
Remove Items in Array
Remove Item At Index
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[5]
newNameList.remove(at: 5) newNameList[5] |
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 |
Example 2:
numberList
numberList[3] let removedNumber = numberList.remove(at: 3) numberList removedNumber |
Remove Sub Range
To remove a range of multiple item, we can use the method removeSubrange. The syntax is as follows:
<array>.removeSubrange(<range_of_items_to_remove>)
Please note that the method do not return anything.
Example:
// Remove item from Johnson to Williams
let indexJohnson = newNameList.index(of: "Johnson")! let indexWillams = newNameList.index(of: "Willams")! let rangeToRemove = indexJohnson...indexWillams newNameList.removeSubrange(rangeToRemove) newNameList |
Example 2:
// Remove item from 67 to 23
numberList numberList.removeSubrange(numberList.index(0, offsetBy: 3)...numberList.index(0, offsetBy: 6)) numberList |
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()
For the following example, we are using back the original list
var numberList = [12,34,54,67,43,89,23,38,72]
var newNameList = ["Smith", "Richards", "Carpenters", "Johnson", "Jones", "Willams", "Taylor"] |
Example:
let lastItemRemoved = newNameList.removeLast()
lastItemRemoved |
Example 2:
let lastNumberRemoved = numberList.removeLast()
lastNumberRemoved |
We can remove more than one item using remove last. We use the method removeLast(n:) where n is the number of item to remove. The syntax is as follows:
<array_name>.removeLast(<number_of_item_to_remove>)
Please note that for this method there will be no return of removed item. If we want to hold the removed item temporary, we need to extract them first before removal.
Example:
newNameList
newNameList.removeLast(3) newNameList |
Example 2:
numberList
numberList.removeLast(4) numberList |
Remove First Item in Array
Similarly, we can also use the method .removeFirst() to remove the first item in an array. Similarly, the method also return the value of the removed item.
Syntax:
<array_name>.removeFirst()
For the following example, we are using back the original list
var numberList = [12,34,54,67,43,89,23,38,72]
var newNameList = ["Smith", "Richards", "Carpenters", "Johnson", "Jones", "Willams", "Taylor"] |
Example:
newNameList
let firstItemRemoved = newNameList.removeFirst() firstItemRemoved newNameList |
Example 2:
numberList
let firstNumberRemoved = numberList.removeFirst() firstNumberRemoved numberList |
We can remove more than one item using remove first. We use the method removeFirst(n:) where n is the number of item to remove. The syntax is as follows:
<array_name>.removeFirst(<number_of_item_to_remove>)
Please note that for this method there will be no return of removed item. If we want to hold the removed item temporary, we need to extract them first before removal.
Example:
newNameList
newNameList.removeFirst(2) newNameList |
Example 2:
numberList
numberList.removeFirst(4) numberList |
Remove All or Purge Existing Array
We can remove all item by using the method removeAll. The syntax is as follows:
<array_name>.removeAll
Example:
Let's create a new array to remove:
var sampleName = ["John", "Mathew", "anthony", "mark"]
sampleName.isEmpty sampleName.removeAll() sampleName.isEmpty |
Alternatively, we can also 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.
var tempNumberList = [12,34,54,67,43,89,23,38,72]
tempNumberList tempNumberList.isEmpty tempNumberList = [] tempNumberList.isEmpty |
***
No comments:
Post a Comment