BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

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?

Code:

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!

3      

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.

3      

@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

3      

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.