Array Methods in Swift
Or how to do things in one line
For my first post, I wanted to write about something that’s easy to understand, yet very useful and powerful! That’s why I chose to show to you the array methods Swift has to offer for manipulating data in Arrays.
I don’t think there’s any app out there that doesn’t use arrays to “play” with data. Very often, you’ll need to search for a specific value, or set of values and you’ll probably do something like this:
let numbers = [87, 21, 9, -12, 55]
var selectedNumbers: [Int] = []for number in numbers {
if number > 45 {
selectedNumbers.append(number)
}
}
The code above works just fine! It gets the job done! Isn’t it a pity though that it takes 7 lines (yes, I’m counting the empty line too) for such a simple task? Well, here comes Swift to the rescue!
let selectedNumbers = numbers.filter({ $0 > 45 }) // cool, huh?!
That’s just 1 line!!! Way cleaner! Now let’s have a quick look at it…
What filter
does, is to separate the loop
logic from your code, so you only have to take care of the predicate. What filter
is, is an array method that takes a closure
as a parameter. This closure
will run for every element in the array. The $0
represents each individual element of each iteration. This closure
needs to return a Bool
in order to know which elements of the array to return.
In short, you get all elements that satisfy the condition you provide inside the closure.
If you understood how
filter
works, then you’ll find very straightforward how every other array method works!
Next, the map
method
Let’s consider the class below:
class Post: NSObject {
var text: String?
var numberOfLikes: Int?
var numberOfComments: Int?
...
}
Now, if you have an array of Post
s but you only need their text
s, you would do something like this:
// obviously this is an empty array, but imagine it's not
let posts = [Post]()var texts: [String] = []for post in posts {
texts.append(post.text ?? "")
}
That is exactly when map
shines:
let texts = posts.map({ $0.text ?? "" })
You specify which property you want and voilà! And of course you can use it with any type of value that contains multiple properties, like a Dictionary
:
let posts = [
["text" : "This is a text", "numberOfLikes" : 2],
["text" : "This is another text", "numberOfLikes" : 20],
["text" : "This is a text also", "numberOfLikes" : 12]
]let texts = posts.map({ $0["text"] as? String ?? "" })
Moving on to first
Unlike filter
, first
–as the name suggests– brings you the first element of the array and you can call it either with a predicate, specifying which element you want, or without and just get the first one. For example:
let numbers = [87, 21, 9, -12, 55]
print(numbers.first) // Optional(87)
Alternatively, you can specify a predicate like we have before:
let numbers = [87, 21, 9, -12, 55]
print(numbers.first(where: { $0 < 10 })) // Optional(9)
There’s also the
last
method which works exactly likefirst
.
Now let’s have a quick look on some other useful array methods:
shuffle
randomly rearranges the order of an array’s elements, on place (there’s alsoshuffled
, which creates and returns a new array instead)reverse
reverses the order of an array’s elements, on place (there’s alsoreversed
, which creates and returns a new array instead)sort
sorts an array based on the given predicate, on place
E.g. sort an array in descending orderarray.sort(by: { $0 > $1})
(there’s alsosorted
, which creates and returns a new array instead)removeAll
with or without predicate
Epilogue
As you can see, there’s so much you can do with arrays in Swift! I hope, next time you’ll find yourself needing to transform or search an array, you’ll fight the urge of doing it yourself and try to benefit from what Swift has to offer!
See ya in the next one (hopefully 😁)