How to Filter an Array in Swift

⋅ 1 min read ⋅ Swift Array

Table of Contents

Swift Array has an instance method, filter(_:), that removes unwanted elements from the resulting array.

The resulting array that pass the filter(_:) contain only the elements that you want.

How to use Array filter

Array filter has the following signature.

func filter(_ isIncluded: (Self.Element) throws -> Bool) rethrows -> [Self.Element]
  • filter(_:) accepts an isIncluded closure which decided which element we want to include in the final array.
  • Each element in the array will pass through this isIncluded closure.
    • If you want to keep that element, you return true from that closure.
    • If you want to remove that element, you return false from that closure.

It is easier to understand this with an example.

Example

Let's say we have an array of people's names, and we want only the names shorter than four characters.

let names = ["Alice", "Bob", "John"]

let shortNames = names.filter { name in
if name.count < 4 {
// 1
return true
} else {
// 2
return false
}
}
print(shortNames)
// ["Bob"]

1 We return true for an element we want to keep. In this case, we want to keep a name shorter than four characters, name.count < 4.
2 For other names, we return false to discard them.

The resulting array contains only names shorter than four characters which is only **"Bob"**in this case.

You can easily support sarunw.com by checking out this sponsor.

Sponsor sarunw.com and reach thousands of iOS developers.

Summary

In summary, to filter an array, you pass a closure telling which element you want to keep in the final array.

  • Return true, if you want to keep it.
  • Return false to discard.

Read more article about Swift, Array, or see all available topic

Enjoy the read?

If you enjoy this article, you can subscribe to the weekly newsletter.
Every Friday, you'll get a quick recap of all articles and tips posted on this site. No strings attached. Unsubscribe anytime.

Feel free to follow me on Twitter and ask your questions related to this post. Thanks for reading and see you next time.

If you enjoy my writing, please check out my Patreon https://www.patreon.com/sarunw and become my supporter. Sharing the article is also greatly appreciated.

Become a patron Buy me a coffee Tweet Share
Previous
Bookmark in Xcode 15

Xcode 15 brings one of the great features of Xcode, the ability to bookmark your code.

Next
Floating Action Button in SwiftUI

iOS doesn't have a Floating Action Button, but we can easily recreate it using what we have in SwiftUI.

← Home