‘where’ clauses in Swift

Posted by

Back when I was a .net developer, one of my favourite things I loved was the introduction of Linq queries.

The simplicity of being able to sort an array of objects as you were enumerating always gave me a certain sense of satisfaction, that and when my mentor first saw me making use of them as junior – it earned me some brownie points too.

More information on Linq queries can be found at


Jump forward a few years and my then day job now consisted of Objective-C and the meme “one does not simply call a method in objective-c” was a part of my daily life.

I enjoyed my new career but missed certain aspects of the .net framework and the C# language – especially things like Linq queries. Few years later and along came Swift – although a major step away from the likes of Objective-C – I felt a certain warm and familiar feeling to a lot of the syntax.

And one of those familiar feelings was the introduction of the ‘where’ clause when within a for each loop.

Let’s see it in action

Now, not quite a Linq query – but certainly familiar territory, we’ll assume we have an array of a Magazine() object – which is already pre-populated with some content. But ultimately I only care about a certain type of magazine, we could do the following;

for magazine in magazines {
    if magazine.type == .electronic {

Which in the big picture of things is just fine, or we could be really be ‘clean code cool’ and streamline it, like so…

for magazine in magazines where magazine.type == .electronic {

Nice and simple, but what about Swift’s new Array.forEach offering;

magazines.forEach { (magazine) in

Our ‘where’ clause has no place here, however if we were insisting on using this syntax and additionally planning on much more complex logic, we could simply create a function that we can call from within our forEach, like so;

// Swift Array ForEach

private func processSubscription(_ magazine: Magazine) {
    if magazine.type == .electronic {
    // ... Add some other custom logic

But unless you are really going to utilise the power of creating another function, your best to just re-write forEach loop to the more traditional one.

More information on Swift’s forEach can be found here:



A Swift Playground with the above example can be found here.

Final note

When often asked how best to switch between programming languages or even move from one to another as part of a new role or project, I’ll often discourage side by side comparisons.

The reason for this being, the origin of an API call to perform a specific task could be very different and comparing to a possible counterpart can sometimes lead you to mis-interpate the desired effect.

However on some occasions it’s okay to do so, especially when you still secretly 💛 the other language.


C. 🥃