Arrays are fundamental building blocks of apps. In this article you’ll learn how you can use arrays in your Swift code. We’ll discuss:
Swift program that uses 2D array with subscript in class class WorldMap var storage = Int init // Create a 100 by 100 two-dimensional array. Use append calls. In the example above numbers had 6 elements and after the replacement of the subsequence 2.4 (3, 4, 5) it had 5. Thanks to Swift’s type inference, you don’t have to declare the type of an array if you initialize it with something other than an empty array literal. Swift provides three primary collection types, known as arrays, sets, and dictionaries, for storing collections of values. Arrays are ordered collections of values. Sets are unordered collections of unique values. Dictionaries are unordered collections of key-value associations.
- How to create arrays, with literal syntax and initializers
- How you can modify an array by adding, removing and replacing elements
- How to iterate over array elements by using a
for
loop
Ready? Let’s go.
Creating an Array
![Swift 4 2d Array Swift 4 2d Array](https://www.codegrepper.com/codeimages/javascript-two-dimensional-array.png)
In computer programming, arrays are numbered lists (or “collections”) of items with the same type. A variable contains one value, and an array can hold many values. Let’s get started with the syntax to create an array.
Here’s an example:
let names = ['Arthur', 'Ford', 'Trillian', 'Zaphod', 'Marvin']
print(names)
print(names)
In the above code, two things happen:
- First, we’re creating an array with the
[..]
literal syntax. This array is assigned to the constantnames
. - Then, we’re printing out the value of
names
. This outputs the array to the Console or debug area.
What’s a literal? A literal value is an expression that’s used exactly as it is. It’s why they’re called a “literal”. In Swift, literals help you constuct code without using complex syntax.
A few examples of literals:
In the above code, we’re creating 3 constants with 3 literal values: an integer, a double and a string. You’re looking at the literal values of these types; that’s why they’re called literals. You’re literally writing integers, doubles and strings in your code.
Back to arrays. The array literal starts with an opening square bracket
[
, followed by zero, one or more elements, and a closing square bracket ]
. Like this:Array’s have fixed types, just like any other variable in Swift. That means that every element in an array has the same type, that cannot be changed once set. All array elements must have the same type, too.
In the above examples, every item has a fixed type:
String
, Int
and Double
. Therefore, the types of the months
, scores
and fraction
arrays are [String]
, [Int]
and [Double]
respectively.Thanks to type inference, you often do not have to explicitly provide the type of a variable when declaring it. Keep in mind that every variable in Swift has a type, even when you don’t explicitly provide it.
How do you create an empty array? Dictionary english russian. Here’s how:
In the above example we’re using the array type
[Int]
together with parentheses ()
. This is called initializer syntax and it’s very similar to creating new objects, i.e. you use the object type in conjuction with ()
, like let tweet = Tweet()
.The
[String]
type is a shorthand for the type Array<String>
. And yes, you’ve guessed it right: arrays are generics!Learn how to build iOS apps
Get started with iOS 14 and Swift 5
Sign up for my iOS development course, and learn how to build great iOS 14 apps with Swift 5 and Xcode 12.
Adding and Removing Array Items
We’ve discussed before that arrays are essentially collections of items with the same type. Every element has a numeric index, starting at 0. Let’s go back to that first example, this one:
var names = ['Arthur', 'Ford', 'Trillian', 'Zaphod', 'Marvin']
print(names)
print(names)
When we write out their indices and values, this is what you get:
Here’s how you add an item to the
names
array:You use the
append(_:)
function to add a new item onto the end of the array. This item must have the same type as the other items in the collection, i.e. String
. You can also use the addition assign operator+=
like this:Fun Fact: You can combine two arrays of similar types with the addition operator
+
. As such, you’ll see in the above code that the +=
operator actually combines the names
array with a new array of one element!Can you also remove items from an array? Of course! You’ll need the index of the item for that. Like this:
This will remove the
'Trillian'
item from the array, because that’s the item with index no. 2.Here’s something counter-intuitive: the
'Trillian'
element is the third item in the names
array. Yet, it has index number 2
– why is that? It’s because arrays are zero-indexed. They start with index 0
, so any n-th item has index n - 1
. Confusing? You’ll get used to it soon enough!Inserting items into an array is similar to adding and removing items. Here’s how:
This will insert the new name at index no. 4. This means that the item that was at position 4 will now shift one position to the right. It won’t get replaced; we’re inserting an item.
Here’s an interactive Swift sandbox for you to play with:
var names = ['Arthur', 'Ford', 'Trillian', 'Zaphod', 'Marvin']
names.append('Eddie')
names += ['Heart of Gold']
names.remove(at: 2)
names.insert('Humma Kavula', at: 4)
print(names)
names.append('Eddie')
names += ['Heart of Gold']
names.remove(at: 2)
names.insert('Humma Kavula', at: 4)
print(names)
Getting and Changing Array Items
Here’s what we’ve discussed so far:
- Creating arrays, and their types
- Appending items to arrays
- Removing items from arrays
- Inserting items into arrays
Every one of these items involves array indices, and it’s worth it to discuss that. Indices are the numeric “labels” that every item gets, starting at
0
.Array indices are consecutive, so you can’t insert an item at index
99
for an array that has only 10 items. Likewise, when you remove an item from an array, the items on the right of the removed item will shift one position to the left.It’s easiest to imagine array items on a line, with the left side starting at
0
. It then makes sense to think of “left” and “right”. Spending some time to get to know how array indices work will definitely help you learn iOS development better, and it’ll save you from some crazy bugs in the future.Let’s get back to arrays. You can read items from an array by using the item index. Like this:
That
names[2]
part is called subscript syntax. You can access any array element this way, i.e. with array[index]
. We can also use it to modify an array. Like this:Here’s an interactive example:
var names = ['Arthur', 'Ford', 'Trillian', 'Zaphod', 'Marvin']
names[2] = 'Prostetnic Vogon Jeltz'
print(names)
names[2] = 'Prostetnic Vogon Jeltz'
print(names)
Looping Over an Array
Arrays and loops are like Simon and Garfunkel – they’re great on their own, but also go really well together. Before we start looping over arrays though, let’s check out some useful array properties:
array.count
contains the number of elements in an arrayarray.first
contains the first item of the arrayarray.last
contains the last item of the arrayarray.isEmpty
istrue
when the array is empty
You can use
array.randomElement()
to get a random element from the array (Swift 4.2+). Arrays have a few other useful functions, like first(where:)
and contains(_:)
. You can also manipulate arrays with higher-order functions like map(_:)
and filter(_:)
.Fun Fact: The last index of an array is equal to
array.count - 1
. Make sure you understand why! It’s got something to do with zero-indexing…OK, let’s get back to for loops. A
for
loop lets you iterate over any kind of sequence or collection, including arrays. Here’s an example:The above code will output every item in
names
. Inside the for
loop body you can use the local constant name
as the current item. Every time the loop runs, an item from the names
collection is assigned to name
and the loop body is executed. This let’s you execute some code for every item in the collection.Let’s say you want to calculate the average score for an exam. Like this:
let scores = [8, 7, 9, 3, 4, 9, 7, 5, 8, 3, 5]
var sum = 0
for score in scores {
sum += score
}
let average = Double(sum) / Double(scores.count)
print(average)
var sum = 0
for score in scores {
sum += score
}
let average = Double(sum) / Double(scores.count)
print(average)
Here’s how that code works:
- First, we’re creating an array
scores
of type[Int]
with a bunch of exam scores between 1 and 10. We’re also initializing a variablesum
and set it to zero. - Then, we loop over every item in the
scores
array. Inside the loop, the current collection item is assigned to constantscore
. Thescore
is added tosum
with the+=
operator. - On the last line, we print out the result of
sum / scores.count
. We’re dividing the sum of scores by the number of scores, which gives us the average score. (We’re converting toDouble()
here so the result is a decimal-point number.)
Awesome! Let’s look at another example:
var names = ['Arthur', 'Ford', 'Trillian', 'Zaphod', 'Marvin']
var reversed = [String]()
for name in names {
reversed.append(String(name.reversed()))
}
print(reversed)
var reversed = [String]()
for name in names {
reversed.append(String(name.reversed()))
}
print(reversed)
With the above code we’re reversing the strings in the
names
array. A name like Arthur becomes ruhtrA. Dropshelf 1 3 1 download free. How does it work?- First, we’re initializing two arrays
names
andreversed
. Both are of type[String]
. - Then, we’re looping over
names
. Everyname
is reversed and added to thereversed
array. - Finally, we’re printing out the value of
reversed
.
Awesome!
Learn how to build iOS apps
Get started with iOS 14 and Swift 5
Sign up for my iOS development course, and learn how to build great iOS 14 apps with Swift 5 and Xcode 12.
Further Reading
Arrays are one of the basic building blocks of apps, so it’s crucial to learn about them if you want to master iOS development. Here’s what you’ve learned in this article:
- How to create arrays, using literal syntax and initializers
- Swift code to change, insert and remove array items
- How to iterate array items with a
for
loop
Arrays are part of collections in Swift. We’ve got a few collection types, such as:
Arrays will make more sense when you work with them, so I definitely recommend you check out some of my more intermediate articles about arrays:
How do you find an item in an array in Swift? Let’s find out! In this tutorial you’ll learn how to use the various generic functions to find matching items in an array.
We’ll get into:
- The algorithm that’s used for finding items in an array
- How you can find the first and last indices of matching array items
- How to find items if you don’t exactly know what you’re looking for, with functions like
first(where:)
- How to find all items in an array that match a given predicate
Ready? Let’s go.
Manually Finding an Item in an Array
Before we dive into Swift’s ways you can find items in an array, let’s find out how such an algorithm actually works.
This will definitely help your understanding of algorithms and iOS development in general. When you’re learning iOS development, it’s a great idea to set aside some time to learn how commonly used algorithms work.
The challenge is simple: given an array of an arbitrary number of items, find the index of a given value. So, if we have an array of names, your job is to find the index for a particular name. Where’s the name in the array?
Here’s our approach at a glance:
- Loop over every value in the array, from start to end
- Keep track of the current index we’re inspecting
- Compare the current value with the value we’re looking for
- If it’s a match, return the current index, if it’s not, keep going
Here’s what that looks like in Swift code:
let names = ['Ford', 'Arthur', 'Trillian', 'Zaphod', 'Marvin', 'Deep Thought', 'Eddie', 'Slartibartfast', 'Humma Kuvula']
let searchValue = 'Zaphod'
var currentIndex = 0
for name in names
{
if name searchValue {
print('Found (name) for index (currentIndex)')
break
}
currentIndex += 1
}
let searchValue = 'Zaphod'
var currentIndex = 0
for name in names
{
if name searchValue {
print('Found (name) for index (currentIndex)')
break
}
currentIndex += 1
}
This is what happens at the top of the above code:
- We’re initializing an array called
names
of type[String]
, which contains a few names - We’re initializing a string called
searchValue
, this is the name we’re looking for - We’re initializing an integer value called
currentIndex
, which keeps track of the current index inside the loop
Then, we’re using a for loop to loop over every name in the
names
array, with for name in names { ···
. Inside the loop, this happens:- With an if statement the code checks if
name
is equal tosearchValue
. It compares the string values, and evaluates totrue
if they are the same. - When there’s a match, a line is printed out, and we’re stopping the loop with
break
. If we don’t do that, the loop will continue, even though we’ve already found what we’re looking for. - At the end of the loop, the code increases the value of
currentIndex
by one. This way we’re keeping track of the current array index, which goes from0
to the end of the array.
Quite simple, right? The code just loops over every item in the array until it finds what we’re looking for.
The time complexity of the above algorithm is O(n), or linear time, because in the worst case scenario we’re looping over every n items once to find what we’re looking for. The time needed to search the array increases linearly with the number of items in the array. This is about as good as it’s going to get for a collection that doesn’t use a hashmap. If you need a test membership in O(1), check out Set.
We can actually save ourselves some trouble by slightly changing the for loop. And lets turn the code into a Swift function, too.
In the above function we’re using the
enumerated()
function to get a sequence of index-value pairs. This way we can directly get the index
of a particular value
, without needing to keep track of the current index ourselves.And the function directly returns an index when it has found a value, which will stop the loop. When no value could be found, the function returns
nil
. As such, the return type of the function is Int?
. (And note that we’re using function argument labels, too.)You’d use the function like this:
Awesome! Now that we know how the algorithm works, let’s see what Swift functions we can use to find an item in an array.
Learn how to build iOS apps
Get started with iOS 14 and Swift 5
Sign up for my iOS development course, and learn how to build great iOS 14 apps with Swift 5 and Xcode 12.
Finding an Item in an Array with “firstIndex(of:)”
![Array Array](https://petrofilm.com/yahoo_site_admin/assets/images/tyske_soldater_invaderer_Oslo.17260816_std.jpg)
The easiest approach to find an item in an array is with the
firstIndex(of:)
function. Here’s how:You call the
firstIndex(of:)
function on the array you want to search. This function is a generic, so it can be used regardless of the array’s type.Let’s say we’re tired of Zaphod, and we want to replace him with someone else. Here’s how:
In the above code, the index of the value
'Zaphod'
is first searched for in the names
array. When found, that index is used to replace the value with another string. (Although I have no idea why you’d want a Vogon on your team, unless you like bureaucracy, highways and/or poetry.)Because the
firstIndex(of:)
function searches an array from front to back, it’ll always return the index of the first match it finds. If you want to get the last match in an array, you can use the lastIndex(of:)
function.Finding an Item in an Array with “firstIndex(where:)”
What if you don’t know exactly what you’re looking for? That’s where the
firstIndex(where:)
function comes in. This function takes a closure, a so-called predicate, as a parameter to search the array for matches.Here’s an example:
let grades = [8, 9, 10, 1, 2, 5, 3, 4, 8, 8]
if let index = grades.firstIndex(where: { $0 < 7 }) {
print('The first index < 7 = (index)')
}
if let index = grades.firstIndex(where: { $0 < 7 }) {
print('The first index < 7 = (index)')
}
In the above code we’re working with a
grades
array of integers. We want to know the index of the first array item that’s below 7. We don’t know the exact number we’re looking for, only that it needs to be less than 7.That’s what we use
firstIndex(where: { $0 < 7 })
for. The code between the squiggly brackets is a closure. This closure is executed for every item of grades
, and we’ve found a successful match when it returns true
.Let’s break that down:
- The code
$0 < 7
is a boolean expression that returnstrue
orfalse
. The$0
is shorthand for the first parameter of the closure, i.e. the value in the array that we’re inspecting. - The function starts at the left of the array, so it’ll evaluate
8 < 7
. This isfalse
, so the function moves on to the next item. - It’ll reach
1 < 7
, which istrue
. Because that’s a match, thefirstIndex(where:)
function returns the index of this item, which is3
.
And we’re using optional binding to get the non-optional value from
firstIndex(where:)
if it doesn’t return nil
.The function
firstIndex(where:)
belongs to a group of functions that can select elements from an array that match a given predicate, including:firstIndex(where:)
returns the index of the first item matching a predicatelastIndex(where:)
returns the index of the last item matching a predicatecontains(where:)
returns a boolean indicating if the array contains an element matching a predicateallSatisfy(_:)
returns a boolean indicating if all of the items in the array match a predicatefirst(where:)
returns the first item (not an index) of the array that matches a predicatelast(where:)
returns the last item (not an index) of the array that matches a predicate
Keep in mind that if you want to use the above functions, the items in your array must conform to the
Equatable
protocol. Types that conform to this protocol can be compared with the operator, which is used to check if two items are equal.And your code gets pretty cool, pretty quickly from there. You can use any kind of comparison in the
where
closure. Things like:- Finding if any given string contains a character with
$0.contains('Q')
- Finding if an object’s property matches a value
$0.name 'Dave'
- Finding if a value matches a range pattern with
300..599 ~= $0
Let’s move on!
The syntax for functions like
firstIndex(where:)
is similar to Swift’s higher-order functionsmap(_:)
, reduce(_:_:)
and filter(_:)
.Finding All Items in an Array with “all(where:)”
What if you want to find all items in an array that match a given predicate? The Swift Standard Library does not yet have a simple function for that, but we can of course make our own!
Let’s have a look. Here’s the
all(where:)
function:The
all(where:)
function is an extension for the Array type, with a generic type constraint that says that this extension only applies for array elements that conform to the Equatable
protocol. In other words, you can only use all(where:)
for array items that can be compared with the operator – just like the other firstIndex(where:)
functions.The
all(where:)
function declaration defines a predicate
parameter of closure type (Element) -> Bool
, and it returns an array of type [Element]
. This is exactly the same as the other functions.Inside the function, we’re using a function called compactMap(_:). This function essentially calls a closure on every item in an array (i.e., “map”) and also removes a value when it is
nil
(i.e., “filter”).The expression
predicate($0) ? $0 : nil
will return the value $0
when the predicate closure returns true
, and nil
when it returns false
. Differently said, the closure will only let values pass for which predicate($0)
is true
, i.e. only array items that match the given condition are returned. And that’s exactly what we want!Here’s how you use it:
Awesome!
Learn how to build iOS apps
Swift 4 2d Array C++
Get started with iOS 14 and Swift 5
Sign up for my iOS development course, and learn how to build great iOS 14 apps with Swift 5 and Xcode 12.
Further Reading
Swift 4 2d Array Tutorial
The Swift programming language lets us do programmatic somersaults, cartwheels and saltos – with just a few lines of code. In this tutorial, we’ve begun to understand how these algorithms work, and then applied them to find different bits of data in arrays. Great work!
Swift 4 Sort 2d Array
Want to learn more? Check out these resources: