In programming, an array or a set is nothing but a collection of items/objects – in the case of arrays, also of the same type. Swift, apart from allowing us to store our object in an array or a set, offers us a wide range of functions and methods to manipulate them. In this chapter, we’ll explore the vast capabilities of the Swift libraries and find ways to make the most out of our object collections.
8.1 Append array to array
Problem
I want to append an array to an existing array.
Solution
Let’s initialize our array.
var a = [1,2,3]
var b = [4,5,6]
And append the new array.
Let’s print out the resulting arrays (Array ‘b’ will be exactly the same – we didn’t do anything to it, did we?)
print("a: (a)")
print("b: (b)")
How It Works
Appending an array to an
existing array can be done with the
+= operator
.
a: [1, 2, 3, 4, 5, 6]
b: [4, 5, 6]
8.2 Append item to array
Problem
I want to append an item to an existing array.
Solution
First approach: Using the
+= operator.
var first = [1,2,3]
first += [4]
Second approach: Using the
append method.
var second = [1,2,3]
second.append(4)
print("Second: (second)")
How It Works
Appending an item to an existing
array can be done either with the
+= operator or using the Array’s
append method.
First: [1, 2, 3, 4]
Second: [1, 2, 3, 4]
8.3 Check if array contains item
Problem
I want to check if an array contains a specific item.
Solution
First, we initialize our example array with some values.
Now, let’s see...
if a.contains(3) {
print("Yes, our array contains the number 3")
} else {
print("Nope, the array doesn't contain the number 3")
}
How It Works
To check if an array contains a particular
element, we can use its
contains method.
Yes, our array contains the number 3
8.4 Check if array is empty
Problem
I want to check if an array is empty.
Solution
First, we initialize our example array with some values.
Now, let’s see...
if a.isEmpty {
print("Our array is empty :(")
} else {
print("Of course it's not empty - we just created it!")
}
How It Works
To check if an array is
empty, we can use its
isEmpty property.
Of course it's not empty - we just created it!
8.5 Check if object is array
Problem
I want to check if an object is of type Array.
Solution
First, we initialize our example “object” – let’s make it an array, as expected.
Now, let’s see...
if a is [Int] {
print("Yes, it's an integer array. Yay!")
} else {
print("Oh, no, this is not an array!")
}
How It Works
To check if an object is of type
Array, we can use an
X is Array or
X is [type] statement.
Yes, it's an integer array. Yay!
8.6 Check if two arrays are equal
Problem
I want to check if two different arrays are equal.
Solution
First, we initialize our arrays.
let a = [1,2,3]
let b = [4,5,6]
Let’s see...
if a == b {
print("Yep, the arrays are equal")
} else {
print("Nope, they are different arrays")
}
How It Works
To compare two arrays and check if they are
equal, we can use the
== comparison
operator.
Nope, they are different arrays
8.7 Check if two tuples are equal
Problem
I want to check if two different tuples are equal.
Solution
First, we initialize our tuples.
let a = (1, "one")
let b = (2, "two")
Let’s see...
if a == b {
print("Yep, the tuples are equal")
} else {
print("Nope, they are different tuples")
}
How It Works
To compare two
tuples and check if they are equal, we can use the
== comparison
operator.
Nope, they are different tuples
8.8 Combine two arrays into array of tuples
Problem
I want to combine two different arrays into an array of tuples, with the elements from both of the initial arrays.
Solution
Let’s initialize our test arrays.
let english = ["one", "two", "three", "four", "five"]
let spanish = ["uno", "dos", "tres", "cuatro", "cinco"]
Time to combine them.
let result = zip(english, spanish).map { ($0,$1) }
Let’s see the resulting array...
print("Result: (result)")
How It Works
If we have two different arrays and want to combine their
elements in pairs, we can use the
zip function
and then map the resulting pairs into an array of tuples.
Result: [("one", "uno"), ("two", "dos"), ("three", "tres"), ("four", "cuatro"), ("five", "cinco")]
8.9 Combine two arrays into dictionary
Problem
I want to combine two different arrays into one dictionary, containing the elements from both of the initial arrays, in the form of key-value pairs.
Solution
Let’s initialize our test arrays.
let english = ["one", "two", "three", "four", "five"]
let spanish = ["uno", "dos", "tres", "cuatro", "cinco"]
And a dictionary to hold our “glossary.”
var glossary : [String:String] = [:]
Time to combine them.
zip(english, spanish).forEach { glossary[$0] = $1 }
Let’s see the resulting dictionary...
print("Result: (glossary)")
How It Works
If we have two different arrays and want to combine their elements into a dictionary, we can use the
zip function
and then
map the resulting pairs into key-value pairs of a dictionary.
Result: ["three": "tres", "four": "cuatro", "five": "cinco", "one": "uno", "two": "dos"]
8.10 Concatenate arrays
Problem
I want to concatenate two different arrays.
Solution
First, we set some initial values.
let first = [1,2,3]
let second = [4,5,6]
Then, we concatenate them.
let result = first + second
How It Works
Concatenating two or more
arrays can be done, using the
+ operator
.
8.11 Convert array to enumerated sequence
Problem
I want to convert an array to an enumerated sequence.
Solution
First, we initialize our example array with some values.
let arr = ["one", "two", "three", "four"]
Let’s convert it to an enumerated sequence.
let enumerated = arr.enumerated()
Let’s print it out.
for (index,item) in enumerated {
print("(index) => (item)")
}
How It Works
In order to convert an array to an enumerated
sequence, that is: a sequence of
(n, x) pairs, where
n represents a consecutive integer starting at zero, and x represents an element of the sequence, we can use the Array’s
enumerated method
.
0 => one
1 => two
2 => three
3 => four
8.12 Convert array to JSON string
Problem
I want to convert an array to its JSON string representation.
Solution
First, let’s create an example array.
let arr : [Any] = [ 1, "Banana", 2, "Apple", 3, "Orange", 4, "Apricot" ]
// Convert our array to JSON data
let json = try JSONSerialization.data(withJSONObject: arr, options: .prettyPrinted)
// Convert our JSON data to string
let str = String(data: json, encoding: .utf8)
// And if all went well, print it out
print(str ?? "Ooops... Error converting JSON to string!")
}
catch let error
{
print("Error: (error)")
}
How It Works
In order to convert a Swift Array to
JSON, we may use the
JSONSerialization class
.
[
1,
"Banana",
2,
"Apple",
3,
"Orange",
4,
"Apricot"
]
8.13 Convert JSON string to array
Problem
I want to convert a JSON string representation to an Array object.
Solution
First, let’s set some test JSON.
let json = "[ 1, "Banana", 2, "Apple", 3, "Orange", 4, "Apricot" ]"
Then, we convert it to a
Data object.
if let data = json.data(using: .utf8) {
// if everything went fine,
// it's time to convert our Data object to an Array
let result = try? JSONSerialization.jsonObject(with: data, options: []) as! [Any]
// And finally, what about printing out our array?
print(result ?? "Ooops... Error converting JSON!")
How It Works
In order to convert a JSON string to a Swift
Array, we may use the
JSONSerialization class
.
[1, Banana, 2, Apple, 3, Orange, 4, Apricot]
8.14 Create a string from character array
Problem
I want to create a String object from a given Character Array.
Solution
First, we initialize our
Character array.
let arr : [Character] = ["H", "e", "l", "l", "o", "!"]
Convert it to a string, using the
String initializer.
Let’s see what we’ve managed...
How It Works
Technically, a
string is nothing but a
sequence/array of characters. So, we can also create a string from a pure array of characters.
8.15 Create an array from range
Problem
I want to create an array from a given range.
Solution
First, let’s say we want all numbers from 0 up to 4 (including 4).
Then, let’s say we want all numbers from 6 up to 9 (but not including 9).
Time to print out our arrays.
print("a: (a)")
print("b: (b)")
How It Works
Creating an array from a
range is as simple as using the
Array initializer along with the desired range.
a: [0, 1, 2, 3, 4]
b: [6, 7, 8]
8.16 Create an array from stride
Problem
I want to create an array from a given stride.
Solution
First, let’s say we want all numbers from 0 up to 10 (not including 10), with a step of 2 - that is: don’t take all of them, just every 2 of them.
let s = stride(from: 0, to: 10, by: 2)
Now, let’s convert it to an array.
How It Works
Creating an
array from a Stride is as simple as using the
Array initializer along with the desired stride.
8.17 Create an array with literal
Problem
I want to create an array from an Array literal.
Solution
This is an array, with its type automatically inferred.
let a = ["one", "two", "three"]
This is another one, but this time let’s set a type.
let b : [String] = ["un", "dos", "tres"]
Let’s create a mixed array with different types of elements. This time we have to explicitly say it’s of type
[Any]. Otherwise, the compiler will doubt whether that was our intention.
let c : [Any] = ["one", 1, "two", 2]
Let’s see what we’ve managed...
print("a: (a), b: (b), c: (c)")
How It Works
Creating an array from an array literal is as simple as listing your values, separated by commas, surrounded by a pair of square brackets ([..]).
a: ["one", "two", "three"], b: ["un", "dos", "tres"], c: ["one", 1, "two", 2]
8.18 Create an empty array
Problem
I want to create an empty Array object.
Solution
First approach: Use the
[] empty array expression.
Second approach: Use an
Array constructor.
Third approach: “Enforce” its type with
as.
Let’s print our three... empty arrays.
print("a: (a), b: (b), c: (c)")
How It Works
In order to create an empty
array, the only thing you have to specify is the
type of items it’s going to contain. That is
String,
Int, or... anything.
8.19 Create NSArray from Array
Problem
I want to create an NSArray object from a given array.
Solution
First, we initialize our example array with some values.
Let’s convert it to an
NSArray.
let b = NSArray(array: arr)
Let’s try using the NSArray’s ‘hash’ property (not available for Swift pure arrays) to make sure we made it.
print("Final array's hash: (b.hash)")
print("Yep, it's an NSArray!")
How It Works
In order to convert/bridge an Array to an
NSArray, for example, when you need to access APIs that expect data in an
NSArray instance, we can use the
NSArray(array:) initializer
.
Final array's hash: 4
Yep, it's an NSArray!
8.20 Create set from array literal
Problem
I want to create a set from an Array literal.
Solution
Let’s initialize our set.
let a : Set = ["one", "two", "three"]
We may also explicitly declare its element’s type.
let b : Set<String> = ["uno", "dos", "tres"]
Let’s see what we’ve managed...
How It Works
Creating a set from array works pretty much like initializing an
array. That is: listing your values, separated by commas, surrounded by a pair of square brackets (
[..
]).
a: ["one", "three", "two"], b: ["tres", "uno", "dos"]
8.21 Filter an array by condition
Problem
I want to filter a given array’s elements by a specific condition.
Solution
First, we initialize our test array.
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Let’s keep only the odd numbers.
let odd = numbers.filter { $0 % 2 == 1}
And... print the result.
print("The odd numbers only: (odd)")
How It Works
If we have an array and want to filter some of its elements based on some condition, then we can use the Array’s
filter method
along with the appropriate closure.
The odd numbers only: [1, 3, 5, 7, 9]
8.22 Get array element at index
Problem
I want to get an array element at a specific index.
Solution
First, we initialize a test array.
let arr = ["one", "two", "three"]
We want the item at index: 1.
Let’s see...
print("Item at index 1: (item)")
How It Works
To get a particular element at a specific index of an
array, we may use its
subscript.
8.23 Get array of values in dictionary
Problem
I want to retrieve the values in a given dictionary as an array.
Solution
Let’s initialize our test dictionary.
let dict = [
"name" : "John",
"surname" : "Doe",
]
Then, we get its values into an array.
let values = Array(dict.values)
Let’s print the result...
print("Our dictionary values: (values)")
How It Works
A dictionary is a collection of key-value pairs. But what if we want to get just the values? For that, we can use the Dictionary’s
values property
.
8.24 Get array valid indices
Problem
I want to get an array of valid indices for a given array.
Solution
First, we initialize our example array with some values.
Let’s remove the last elements.
Let’s see...
print("The array's valid indices: (indices)")
How It Works
To check an array’s
valid indices, that is: the indices that are valid for subscripting the collection, we can use the Array’s
indices property
.
The array's valid indices: 0..<4
8.25 Get capacity of array
Problem
I want to get the total capacity of a given array.
Solution
First, we initialize our example array with some values.
Let’s remove the last elements.
Let’s now check the array’s capacity.
let capacity = a.capacity
print("The array's capacity: (capacity)")
How It Works
To check the capacity of an array, that is: the total number of elements that the array can contain using its current storage, we can use the Array’s
capacity property
.
8.26 Get element index in array by value
Problem
I want to get the index of a specific element in a given array by its value .
Solution
First, we initialize a test array.
let arr = ["one", "two", "three"]
We want the item at index: 1.
let index = arr.index(of: "two")
If we found it, let’s print its index.
if let i = index {
print("Item 'two' is at index: (i)")
}
How It Works
To get the index of a particular
element – based on its value – we may use the Array’s
index(of:) method
.
Item 'two' is at index: 1
8.27 Get first item from array
Problem
I want to get an array’s first element.
Solution
First, we initialize a test array.
let arr = ["one", "two", "three"]
First approach: Do it with the subscript.
Second approach: Use the first property
.
let b = arr.first ?? "error"
Let’s print out the results...
How It Works
To get the first element in an array, we may use either the subscript or the Array’s
first property
.
a: one, b: Optional("one")
8.28 Get first X items from array
Problem
I want to retrieve the first elements from a given array.
Solution
First, we initialize a test array.
let arr = ["one", "two", "three", "four", "five"]
Let’s get the first three items.
let slice = arr.prefix(3)
Let’s print out the results...
How It Works
To get the first
X elements in an array, we may use the Array’s
prefix method
.
slice: ["one", "two", "three"]
8.29 Get index of item in array
Problem
I want to get the index of a specific item in a given array.
Solution
First, we initialize a test array.
let arr = ["one", "two", "three", "one", "two", "four"]
Then, we get the index of “two.”
let index = arr.index(of: "two")
We must first check that we did find it.
// Let's print out the result
print("First 'two' found at index: (index!)")
}
How It Works
To get the index of the first occurrence of a specific
item within an array, we may use the
index(of:) method
.
First 'two' found at index: 1
8.30 Get indices of item in array
Problem
I want to get the indices (if more than one) of a specific item in a given array.
Solution
First, we initialize a test array.
let arr = ["one", "two", "three", "one", "two", "four"]
Let’s set an array where we’ll keep our indices.
Time to loop through our array and look for ‘two’s.
for (index,item) in arr.enumerated() {
// If it's the item we're looking for,
// add it to our 'indices' array
if item == "two" { indices.append(index) }
}
Let’s print out the result...
print("'two' found at indices: (indices)")
How It Works
To get the indices of all occurrences of a specific
item within an array, we may loop through the array, and check the items one by one.
'two' found at indices: [1, 4]
8.31 Get last item from array
Problem
I want to get the last element of a given array.
Solution
First, we initialize a test array.
let arr = ["one", "two", "three"]
First approach: Do it with the subscript.
Second approach: Use the last property.
Let’s print out the results...
print("a: (a), b: (String(describing:b))")
How It Works
To get the last element in an
array, we may use either the
subscript or the Array’s
last property
.
a: three, b: Optional("three")
8.32 Get last X items from array
Problem
I want to retrieve the last elements from a given array.
Solution
First, we initialize a test array.
let arr = ["one", "two", "three", "four", "five"]
Let’s get the last three items.
let slice = arr.suffix(3)
Let’s print out the results...
How It Works
To get the
last X elements in an array, we may use the Array’s
suffix method.
slice: ["three", "four", "five"]
8.33 Get maximum value in array
Problem
I want to retrieve the maximum value from a number array.
Solution
First, we initialize a test array.
Then we get the maximum item.
Let’s find out...
print("Maximum: (String(describing:m))")
How It Works
To get the maximum
element in an array, we may use the Array’s
max method
.
8.34 Get minimum value in array
Problem
I want to retrieve the minimum value from a number array.
Solution
First, we initialize a test array.
Then we get the minimum item.
Let’s find out...
print("Minimum: (String(describing:m))")
How It Works
To get the minimum element in an
array, we may use the Array’s
min method
.
8.35 Get random item from array
Problem
I want to retrieve a random element from a given array.
Solution
First, we initialize a test array.
var fruit = ["pineapple", "banana", "apple", "mango", "apricot"]
Then, we get a random fruit from our basket.
var rnd = Int(arc4random()) % fruit.count
var randomFruit = fruit[rnd]
Let’s print it out...
print("Here's the fruit I picked for you: (randomFruit)")
How It Works
To get a random element from an
array, we’ll be using the
arc4random function.
Here's the fruit I picked for you: apple
8.36 Get size of array
Problem
I want to get the size of a given array.
Solution
First, we initialize our example array with some values.
Now, let’s count how many items we’ve got.
print("The array contains (a.count) elements")
How It Works
To check the size of an
array, we can use its
count property.
The array contains three elements
8.37 Get tuple element by index
Problem
I want to retrieve a tuple element by its index.
Solution
First, we initialize a test tuple.
let tuple = ("one", "two", "three")
We want the item at index: 1.
Let’s see...
print("Item at index 1: (item)")
How It Works
To get a particular element at a specific index of a
tuple, we may use its index.
8.38 Get tuple element by pattern matching
Problem
I want to get a specific tuple element by matching against a given pattern.
Solution
First, we initialize a test tuple.
let tuple = ("one", "two", "three")
We want the item at index: 1 (the second element) so that we can safely ignore everything else.
Let’s see...
print("Item at index 1: (item)")
How It Works
To get a particular element at a specific location within a tuple, we may reassign it to another variable and only get the part we want.
8.39 Insert item at array index
Problem
I want to insert an element at a specific array index.
Solution
First, we initialize a test array.
var arr = ["one", "two", "three"]
Then we insert our new item at index: 1 (after “one” and before “two”).
Let’s see our new array...
How It Works
To insert a particular item at some specific index in an existing
array , we may use the Array’s
insert(_,at:) method
.
Array: ["one", "new", "two", "three"]
8.40 Join array items using separator
Problem
I want to join the elements of a string array, using a specific separator.
Solution
First, we initialize our test array.
let arr = [
"bananas",
"apples",
"apricots",
"pineapples",
"oranges"
]
Let’s join them into a string, using a comma as a
separator.
let fruit = arr.joined(separator: ",")
How It Works
In order to join an array’s
items into a string, we can use the Array’s
joined(separator:) method
.
bananas,apples,apricots,pineapples,oranges
8.41 Loop through an array in reverse
Problem
I want to loop through an array’s element in reverse.
Solution
Let’s initialize our array, with some values.
let arr = ["one", "two", "three"]
Iterate through the array.
for element in arr.reversed() {
print(element)
}
How It Works
In order to loop through an array in
reverse, we can use a
for-in statement along with our array... reversed, using the Array’s
reversed method
.
8.42 Loop through an array with index
Problem
I want to loop through an array’s elements and keep track of the element’s index at the same time.
Solution
Let’s initialize our array, with some values.
let arr = ["one", "two", "three"]
Iterate through the array, while keeping the items’ index: Use
.enumerated() to convert your array to iterable key-value pairs.
for (index,element) in arr.enumerated() {
print("Item at (index): (element)")
}
How It Works
In order to loop through an array with its index, we can use a
for-in statement along with our array... enumerated, that is: using the Array’s
enumerated method
, which will assign an index, to each one of our array’s elements.
Item at 0: one
Item at 1: two
Item at 2: three
8.43 Loop through an array
Problem
I want to loop through an array’s elements.
Solution
Let’s initialize our array, with some values.
let arr = ["one", "two", "three"]
Iterate through the array.
for element in arr {
print(element)
}
How It Works
In order to loop through an
array, we can use a
for-in statement.
8.44 Map array values using function
Problem
I want to map an array’s values to a new array using a specific function.
Solution
First, we initialize our test array.
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Now, let’s say we want the squares of the above numbers. That is: to map each of the above numbers to its squares.
let squares = numbers.map { $0 * $0 }
And... print the result.
print("Our numbers: (numbers)")
print("Squared: (squares)")
How It Works
If we have an array and want to map its values to new ones, using a specific function, then we can use the Array’s
map method
along with the appropriate closure.
Our numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Squared: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
8.45 Pop last item from array
Problem
I want to retrieve the last element from an array, and remove it from that array.
Solution
First, we set some initial value.
var arr = ["one", "two", "three", "four", "five"]
Let’s pop the last element.
let lastElement = arr.removeLast()
Let’s see...
print("Popped element: (lastElement)")
print("Resulting array: (arr)")
How It Works
In order to pop an array’s last element, we can use the Array’s
removeLast method
.
Popped element: five
Resulting array: ["one", "two", "three", "four"]
8.46 Prepend item to array
Problem
I want to add an element at the beginning of a given array.
Solution
First, we initialize our array.
var fruit = ["banana", "apple", "mango", "apricot"]
Then, we prepend our new item. That is: Insert it at index 0.
fruit.insert("pineapple", at: 0)
Let’s see our new array...
How It Works
Prepending an item to an existing array can be done, using the Array’s
insert method
.
Result: ["pineapple", "banana", "apple", "mango", "apricot"]
8.47 Reduce array to a single value
Problem
I want to “reduce” an array of numbers to a single value.
Solution
Let’s initialize our example array.
let numbers = [1, 2, 3, 4, 5, 6]
What we want to do is basically add up all the elements. So, we set an initial value, followed by the closure that describes the action to be performed on our array.
Tip: Reduce starts with an initial value, performs some action to this value and the first value it encounters in our array, and then proceeds recursively using the result. And so on... until there are no more elements in our array...
let result = numbers.reduce(0, { $0 + $1 })
Let’s see the result...
print("Result: (result)")
How It Works
If we want to combine all elements in an array and reduce it to a single value, we can use the Array’s
reduce method
.
8.48 Remove all items from array
Problem
I want to remove all elements from a given array.
Solution
First, we initialize a test array.
var arr = ["one", "two", "three"]
Then we remove all of its contents.
Let’s see our new - empty – array...
How It Works
To remove all values from an existing array (basically, to empty it), we may use the Array’s
removeAll method
.
8.49 Remove array item by index
Problem
I want to remove a specific element from a given array, by its index.
Solution
First, we initialize a test array.
var arr = ["one", "two", "three"]
Then we remove the item at index: 1.
Let’s see our new array...
How It Works
To remove a particular item at some specific
index in an existing array, we may use the Array’s
remove(at:) method
.
8.50 Remove array item by value
Problem
I want to remove a specific element from a given array, by its value.
Solution
First, we initialize a test array.
var arr = ["one", "two", "three"]
Then, we remove all “two” values.
arr = arr.filter { $0 != "two" }
Let’s see our new array...
How It Works
To remove a particular value in an existing
array, we may use the Array’s
filter method
.
8.51 Remove duplicates from array
Problem
I want to remove all duplicate elements from a given array.
Solution
First, we initialize a test array.
var initial = [6, 3, 1, 2, 4, 1, 2, 3, 6, 5, 1, 2]
Then, we remove any duplicates.
var unique = Array(Set(initial))
Let’s print our new no-duplicates array.
print("Before: (initial)")
print("Unique: (unique)")
How It Works
To remove all duplicates from a given array, pretty much like PHP’S
array_unique, we may use a simple
trick: convert the array to a set (by definition they contain unique elements) and then back to an array.
Before: [6, 3, 1, 2, 4, 1, 2, 3, 6, 5, 1, 2]
Unique: [6, 5, 2, 3, 1, 4]
8.52 Reverse an array
Problem
I want to reverse an array’s elements.
Solution
First, we set some initial value.
let arr = ["one", "two", "three", "four", "five"]
Time to reverse it.
let reversed = Array(arr.reversed())
Let’s see...
print("(arr) => (reversed)")
How It Works
In order to reverse an array, we can use the Array’s
reversed method
.
["one", "two", "three", "four", "five"] => ["five", "four", "three", "two", "one"]
8.53 Set array element at index
Problem
I want to set an element’s value at a specific index of a given array.
Solution
First, we initialize a test array.
var arr = ["one", "two", "three"]
We want the set the item at index: 1.
How It Works
To assign a particular element at a specific
index of an array some new value, we may use its
subscript.
Array: ["one", "<new>", "three"]
8.54 Shift first item from array
Problem
I want to retrieve and “shift” the first element of a given array.
Solution
First, we set some initial value.
var arr = ["one", "two", "three", "four", "five"]
Let’s shift the first element.
let firstElement = arr.removeFirst()
Let’s see...
print("First element: (firstElement)")
print("Resulting array: (arr)")
How It Works
In order to shift/pop an array’s first element, we can use the Array’s
removeFirst method
.
First element: one
Resulting array: ["two", "three", "four", "five"]
8.55 Shuffle an array
Problem
I want to – randomly – shuffle an array’s elements.
Solution
First, we initialize a test array.
var initial = [1, 2, 3, 4, 5, 6]
Then we shuffle it.
var shuffled = initial.sorted { _,_ in Int.random(in: 0..<1000) < Int.random(in: 0..<1000) }
Let’s print our new no-duplicates array.
print("Before: (initial)")
print("Shuffled: (shuffled)")
How It Works
To shuffle an array, aka randomize the order of its elements, we’ll be using the arc4random function
.
Before: [1, 2, 3, 4, 5, 6]
Shuffled: [5, 2, 3, 4, 1, 6]
8.56 Sort array of dictionaries by field in ascending order
Problem
I want to sort a given array of dictionaries, by some specific dictionary field, in ascending order.
Solution
First, we initialize a test array.
var members = [
["name": "John", "age": 30],
["name": "Jane", "age": 39],
["name": "Angela", "age": 18],
["name": "Nick", "age": 59]
]
Now let’s say we want to sort our members list, by age.
var sorted = members.sorted { ($0["age"] as! Int) < ($1["age"] as! Int) }
Let’s print our sorted array...
print("Sorted: (sorted)")
How It Works
To sort an array containing
dictionaries, by dictionary field, in ascending order, we may use the Array’s
sorted method, along with the appropriate closure.
Sorted: [["name": "Angela", "age": 18], ["name": "John", "age": 30], ["name": "Jane", "age": 39], ["name": "Nick", "age": 59]]
8.57 Sort array of dictionaries by field in descending order
Problem
I want to sort a given array of dictionaries, by some specific dictionary field, in descending order.
Solution
First, we initialize a test array.
var members = [
["name": "John", "age": 30],
["name": "Jane", "age": 39],
["name": "Angela", "age": 18],
["name": "Nick", "age": 59]
]
Now let’s say we want to sort our members list, by age.
var sorted = members.sorted { ($0["age"] as! Int) > ($1["age"] as! Int) }
Let’s print our sorted array...
print("Sorted: (sorted)")
How It Works
To sort an array containing dictionaries, by dictionary field, in descending order, we may use the Array’s
sorted method
, along with the appropriate closure.
Sorted: [["name": "Nick", "age": 59], ["name": "Jane", "age": 39], ["name": "John", "age": 30], ["name": "Angela", "age": 18]]
8.58 Sort array of numbers in ascending order
Problem
I want to sort a given array of numbers, in ascending order.
Solution
First, we initialize a test array.
var initial = [6, 3, 1, 2, 4]
Then we sort the array and get the resulting array.
var sorted = initial.sorted()
Let’s print our sorted array...
print("Before: (initial)")
print("Sorted: (sorted)")
How It Works
To sort an array containing numeric values, in
ascending order, that is: from smallest to largest, we may use the Array’s
sorted method.
Before: [6, 3, 1, 2, 4]
Sorted: [1, 2, 3, 4, 6]
8.59 Sort array of numbers in descending order
Problem
I want to sort a given array of numbers in descending order.
Solution
First, we initialize a test array.
var initial = [6, 3, 1, 2, 4]
Then, we sort the array and get the resulting array.
var sorted = initial.sorted(by: >)
Let’s print our sorted array...
print("Before: (initial)")
print("Sorted: (sorted)")
How It Works
To sort an array containing numeric values, in descending order, that is: from largest to smallest, we may use the Array’s
sorted method
.
Before: [6, 3, 1, 2, 4]
Sorted: [6, 4, 3, 2, 1]
8.60 Sort array of strings in ascending order
Problem
I want to sort a given array of strings, lexicographically, in ascending order.
Solution
First, we initialize a test array.
var initial = ["one", "two", "three", "four", "five", "six"]
Then, we sort the array and get the resulting array.
var sorted = initial.sorted()
Let’s print our sorted array...
print("Before: (initial)")
print("Sorted: (sorted)")
How It Works
To sort an array containing string
values, in ascending lexicographic order, that is: from the one that’d come first in a dictionary to that which would come last, we may use the Array’s
sorted method, pretty much as we’d do for a number array.
Before: ["one", "two", "three", "four", "five", "six"]
Sorted: ["five", "four", "one", "six", "three", "two"]
8.61 Sort array of strings in descending order
Problem
I want to sort a given array of strings, lexicographically, in descending order.
Solution
First, we initialize a test array.
var initial = ["one", "two", "three", "four", "five", "six"]
Then, we sort the array and get the resulting array.
var sorted = initial.sorted(by: >)
Let’s print our sorted array...
print("Before: (initial)")
print("Sorted: (sorted)")
How It Works
To sort an array containing string values, in descending lexicographic order, that is: from the one that’d come last in a
dictionary to that which would come first, we may use the Array’s
sorted method, pretty much as we’d do for a number array.
Before: ["one", "two", "three", "four", "five", "six"]
Sorted: ["two", "three", "six", "one", "four", "five"]
8.62 Swap items in array by index
Problem
I want to swap two elements in a given array, specifying their indices.
Solution
First, we initialize a test array.
var arr = ["zero", "one", "two", "three", "four", "five"]
Then we
swapAt the elements at indices 2 and 3 – meaning: “two” and “three.”
Let’s see our new rearranged array, “three” will appear before “two” now.
How It Works
To swap two elements in an existing array by their
indices, we can use the
swapAt function
with references to the individual elements we want to swap.
Array: ["zero", "one", "three", "two", "four", "five"]
8.63 Write a list comprehension
Problem
I want to write a list comprehension.
Solution
Let’s take this set for example:
E = {x*x | x in {0 ... 10} and x even}.
That is: get a list for all the x’s squared (with x between 0 and 10) where x is even.
Let’s describe our list of evens – squared.
let evenSquared = (0...10).filter { $0 % 2 == 0}
.map { $0 * $0 }
And let’s print our list...
print("Result: (evenSquared)")
How It Works
List Comprehension is nothing but a fancy way of describing the very natural, easy way that a mathematician usually uses to describe a list.
Result: [0, 4, 16, 36, 64, 100]
8.64 Write a lazy list comprehension
Problem
I want to write a “lazy” list comprehension.
Solution
Let’s take this set for example:
E = {x*x | x in {0 ... 10} and x even}.
That is: get a list for all the x’s squared (with x between 0 and 10) where x is even.
However, if we want to do it in pure... functional styling, we’ll have to use lazy evaluation.
Let’s describe our list of evens – squared.
let evenSquared = (0...10).lazy.filter { $0 % 2 == 0}
.map { $0 * $0 }
It’s lazy – so, nothing has been calculated so far.
Let’s make it calculate our result.
let result = Array(evenSquared)
Finally, let’s print our list...
print("Result: (result)")
How It Works
List
Comprehensions is nothing but a fancy way of describing the very natural, easy way that a mathematician usually uses to describe a list. And lazy evaluation, or
call-by-need, is nothing but a strategy that delays the evaluation of an expression until its value is needed.
Result: [0, 4, 16, 36, 64, 100]
8.65 Check if set contains item
Problem
I want to check if a given set contains a specific element.
Solution
First, we initialize our example set with some values.
let fruit : Set = ["banana", "apple", "orange", "pineapple"]
Now, let’s see...
if fruit.contains("banana") {
print("Yes, our set contains bananas!")
} else {
print("Nope, no bananas left! :(")
}
How It Works
To check if a set contains a particular
element, we can use its
contains method.
Yes, our set contains bananas!
8.66 Check if set is empty
Problem
I want to check if a given set is empty.
Solution
First, we initialize our example set with some values from an array.
Now, let’s see...
if a.isEmpty {
print("Our set is empty :(")
} else {
print("Of course it's not empty - we just created it!")
}
How It Works
To check if a set is empty, we can use its
isEmpty property
.
Of course it's not empty – we just created it!
8.67 Check if set is strict subset of another set
Problem
I want to check if a given set is a strict subset of another set.
Solution
First, let’s initialize our test sets.
let animals : Set = ["dog", "cat", "eagle", "salmon", "mosquito"]
let mammals : Set = ["dog", "cat"]
Let’s see if mammals is a strict subset of animals.
if mammals.isStrictSubset(of: animals) {
print("Yep, mammals are a strict subset of animals.")
}
How It Works
To check if a particular set is a
strict subset of another set, that is: if all of our set’s elements of are contained in another set or
sequence, but the two sets are not equal, we can use the Set’s
isStrictSubset(of:) method
.
Yep, mammals are a strict subset of animals.
8.68 Check if set is strict superset of another set
Problem
I want to check if a given set is a strict superset of another set.
Solution
First, let’s initialize our test sets.
let animals : Set = ["dog", "cat", "eagle", "salmon", "mosquito"]
let mammals : Set = ["dog", "cat"]
Let’s see if animals is a strict superset of mammals.
if animals.isStrictSuperset(of: mammals) {
print("Yep, animals are a strict superset of mammals.")
}
How It Works
To check if a particular set is a
strict superset of another
set, that is: if our set contains all the elements of another set or sequence, but the two sets are not equal, we can use the Set’s
isStrictSuperset(of:) method
.
Yep, animals are a strict superset of mammals.
8.69 Check if set is subset of another set
Problem
I want to check if a given set is a subset of another set.
Solution
First, let’s initialize our test sets.
let animals : Set = ["dog", "cat", "eagle", "salmon", "mosquito"]
let mammals : Set = ["dog", "cat"]
Let’s see if mammals is a subset of animals.
if mammals.isSubset(of: animals) {
print("Yep, mammals are a subset of animals.")
}
How It Works
To check if a particular set is a
subset of another set, that is: if all of our set’s elements of are contained in another set or
sequence, we can use the Set’s
isSubset(of:) method
.
Yep, mammals are a subset of animals.
8.70 Check if set is superset of another set
Problem
I want to check if a given set is a superset of another set.
Solution
First, let’s initialize our test sets.
let animals : Set = ["dog", "cat", "eagle", "salmon", "mosquito"]
let mammals : Set = ["dog", "cat"]
Let’s see if animals is a superset of mammals.
if animals.isSuperset(of: mammals) {
print("Yep, animals are a superset of mammals.")
}
How It Works
To check if a particular set is a
superset of another set, that is: if our set contains all the elements of another set or
sequence, we can use the Set’s
isSuperset(of:) method
.
Yep, animals are a superset of mammals.
8.71 Check if two sets are equal
Problem
I want to check if two different sets are equal.
Solution
First, we initialize our sets from arrays.
let a : Set = [1,2,3]
let b : Set = [4,5,6]
Let’s see...
if a == b {
print("Yep, the sets are equal")
} else {
print("Nope, they are different sets")
}
How It Works
To compare two
sets and check if they are equal, we can use the
== comparison
operator.
Nope, they are different sets
8.72 Check if two sets have common items
Problem
I want to check if two different sets have common elements.
Solution
First, we initialize our example sets with some values.
let reptiles : Set = ["chameleon", "snake", "lizard"]
let birds : Set = ["eagle", "crow", "seagull"]
Now, let’s see if these two have any elements in common.
if reptiles.isDisjoint(with: birds) {
print("Well, quite obviously, they have no members in common.")
} else {
print("Yep, there are some common elements - wait, what?!")
}
How It Works
To check if two sets have elements in
common, we can the Set’s
isDisjoint(with:) method
.
Well, quite obviously, they have no members in common.
8.73 Create an empty set
Problem
I want to create an empty Set object.
Solution
First approach: Just declare the type and set to an
empty array.
Second approach: Use a S
et constructor.
Let’s print our empty sets...
How It Works
In order to create an empty
set, the only thing you have to specify is the type of items it’s going to contain. That is
String,
Int, or... anything.
8.74 Create NSSet from Set
Problem
I want to create an NSSet object from a given set.
Solution
First, we initialize our example set.
let a : Set = ["one", "two", "three"]
Let’s convert it to an
NSSet.
Let’s try using the NSSet’s ‘hash’ property (not available for Swift pure sets) to make sure we made it.
print("Final set's hash: (b.hash)")
print("Yep, it's an NSSet!")
How It Works
In order to convert/bridge a Set to an NSSet, for example, when you need to access APIs that expect data in an
NSSet instance
, or need to use some NSSet-specific methods, we can use the
NSSet(set:) initializer
.
Final set's hash: 3
Yep, it's an NSSet!
8.75 Find the difference of two sets
Problem
I want to find the difference of two different sets.
Solution
First, let’s initialize our test sets.
let first : Set = [1, 2, 3, 4]
let second : Set = [3, 4, 5, 6]
Let’s find the difference.
let result = first.subtracting(second)
...and print the resulting set.
print("Result: (result)")
How It Works
To find the difference of two sets, that is: the set that contains the elements of set A, after subtracting the elements of set B, we can use the Set’s
subtracting method
.
8.76 Find the intersection of two sets
Problem
I want to find the intersection of two different sets.
Solution
First, let’s initialize our test sets.
let first : Set = [1, 2, 3, 4]
let second : Set = [3, 4, 5, 6]
Let’s find the intersection.
let result = first.intersection(second)
...and print the resulting set.
print("Result: (result)")
How It Works
To find the intersection of two sets, that is: the set that contains only the common elements of the two sets, we can use the Set’s
intersection method
.
8.77 Find the symmetric difference of two sets
Problem
I want to find the symmetric difference of two different sets.
Solution
First, let’s initialize our test sets.
let first : Set = [1, 2, 3, 4]
let second : Set = [3, 4, 5, 6]
Let’s find the symmetric difference.
let result = first.symmetricDifference(second)
...and print the resulting set.
print("Result: (result)")
How It Works
To find the symmetric difference of two sets, that is: the set that contains the elements in one of the two sets, but not in both of them, we can use the Set’s
symmetricDifference method
.
8.78 Find the union of two sets
Problem
I want to find the union of two different sets.
Solution
First, let’s initialize our test sets.
let first : Set = [1, 2, 3, 4]
let second : Set = [3, 4, 5, 6]
Let’s find the union.
let result = first.union(second)
...and print the resulting set.
print("Result: (result)")
How It Works
To find the union of two sets, that is: the set that contains the elements of both sets, we can use the Set’s
union method
.
Result: [5, 6, 2, 3, 1, 4]
8.79 Get size of set
Problem
I want to get the size of a given set.
Solution
First, we initialize our example set with some values from an array.
Now, let’s count how many items we’ve got...
print("The set contains (a.count) elements")
How It Works
To check the size of a Set, we can use its
count property
.
The set contains 3 elements
8.80 Loop through a set
Problem
I want to loop through a given set’s elements.
Solution
Let’s initialize our Set with some values from an array literal.
let mySet : Set = ["one", "two", "three"]
Iterate through the set elements.
for element in mySet {
print(element)
}
How It Works
In order to loop through a
set, we can use a
for-in statement.
8.81 Remove all items from set
Problem
I want to remove all elements from a given set.
Solution
First, we initialize a test set.
var basket : Set = ["steak", "oranges", "milk"]
Then we remove all of its contents.
Let’s see our new - empty - set.
print("Basket: (basket)")
How It Works
To remove all values from an existing set (basically, to empty it), we may use the Set’s removeAll method
.
8.82 Summary
In this chapter, we learned how we can efficiently manipulate and play with our arrays and sets.
In the next chapter, we’ll be looking into one more of the most used objects in Swift: Dictionaries.