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 trialkevin11
2,535 PointsSwift 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:
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
Joshua Rapoport
8,415 PointsFirst 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)
kevin11
2,535 Pointskevin11
2,535 PointsIt is still not working??? What should i do?
Joshua Rapoport
8,415 PointsJoshua Rapoport
8,415 PointsGot 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()
, notmap()
.It all has to do with the return type. Though both
filter()
andmap()
are capable of iterating through an array of typeInt
,map()
is the one which, like theisOdd
function, returns a Boolean value. Meanwhile,map()
is used to replace each value with an updated one. The reasonmap()
didn't work is because rather than using the returnedBool
to decide whether or not to keep that item, it used theBool
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) usefilter()
, notmap()
.kevin11
2,535 Pointskevin11
2,535 PointsYes!!! Got it. Thanks for the help