NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

iOS Interview Questions

Forums > iOS

I'm looking for help in understanding some of the common iOS interview questions. I recently came across a resources, but I'm still having trouble understanding some of the code examples they provide. Could someone please provide some insight into how the following code works and what the logic behind it is?


let myArray = [1, 2, 3, 4, 5]

let newArray = myArray.filter { (number) -> Bool in
    return number % 2 == 0

Thanks for any help you can provide!


These things can look confusing at first especially when some of Swift's abbreviated syntax is used. The filter function is an example of functional programming (along with map and reduce, etc). In your code the filter function takes each element of myArray in turn, performs a logical check (true or false) and puts those elements that return true, into newArray.

Filter takes a closure as a parameter. This closure is what performs that logical check on each element in myArray. Your code is written using trailing closure syntax so that's why there is no () around the closure. This line:

(number) -> Bool 

is just the signature of the closure and we know that it takes some element and returns true or false. 'number' is just a variable name (of whatever type myArray contains - in this case Int) that will be used inside the closure.

In this case return number % 2 == 0 just checks if each element of myArray is even.

It can be written:

let newArray = myArray.filter { $0 % 2 == 0 }

The signature can be omitted since filter always takes an element and returns a Bool. The variable $0 in place of the formally declared variable name and as usual 'return' can be omitted for a single line of code.

I really hope I haven't made things more complicated.


@Henry's question brings up old memories....

Could someone please provide insight into how the following code works and what the logic behind it is?

Here's a post showing several ways to pass a function into another function. Closures are a shorthand version of a more complex syntax. This post might be beneficial to your interview process if you're familiar with the various syntax.

See -> Functions: Variations on a Theme


Hacking with Swift is sponsored by Judo

SPONSORED Let’s face it, SwiftUI previews are limited, slow, and painful. Judo takes a different approach to building visually—think Interface Builder for SwiftUI. Build your interface in a completely visual canvas, then drag and drop into your Xcode project and wire up button clicks to custom code. Download the Mac App and start your free trial today!

Try now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.