Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Swift Closures Closures and Closure Expressions Using Filter

Swift Closure Challenge?

I am having trouble with this challenge. Here is the objective:

Given an array of integers, called numbers, use the filter function (and the helper function we created) to create a new array containing only odd numbers. Assign this new array to a constant named oddNumbers.

I am unsure of how to do this. There isn't another question for this challenge so there isn't really any help. Please help me. Here is my code:

filter.swift
let numbers = [Int](0...50)

// Enter your code below

func isOdd(i: Int) -> Bool {
if i % 2 == 0 {
return false
} else {
return true
}
}

let numbers = [1,2,3,4,5]
let oddNumbers = numbers.map { isOdd }

1 Answer

First of all, numbers is initialized twice in you code. I'm pretty sure that the reason is that the challenge had already initialized the numbers array as:

let numbers = [Int](0...50)

:and you didn't notice, which is why you wrote the declaration a second time.

The second reason this code isn't working is because you are trying to use closure expression to contain a function that already exists, while putting nothing in the curly braces which would make it a closure. Instead, replace the curly braces in the .map() function with parentheses:

let oddNumbers = numbers.map(isOdd)

It is still not working??? What should i do?

Got it! You were using the wrong function altogether!

In the challenge description, it tells you to "use the filter function." That means it wants you to use the function called filter(), not map().

It all has to do with the return type. Though both filter() and map() are capable of iterating through an array of type Int, map() is the one which, like the isOdd function, returns a Boolean value. Meanwhile, map() is used to replace each value with an updated one. The reason map() didn't work is because rather than using the returned Bool to decide whether or not to keep that item, it used the Bool as an item in the new array. filter() selects, map() replaces.

So recap; (1) initialize numbers only once; (2) parentheses instead of curly braces for the final function; and (3) use filter(), not map().

Yes!!! Got it. Thanks for the help