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

Beating the odds

I'm stuck! This works when I tried it in Playground, but not here.

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

let isOdd = numbers.map({(i: Int) -> Bool in return ((i % 2) - 1 ) == 0})

2 Answers

Martin Wildfeuer
PLUS
Martin Wildfeuer
Courses Plus Student 11,071 Points

Hey Beth!

Define a function, named isOdd, to check if a number is odd. The function takes a number and returns either true or false depending on if the number is odd or not.

You need to create a function first. This function takes an Int and returns a Bool. In the body, we check whether a number is odd and return the boolean result. Your approach with (i % 2) - 1 ) == 0 is really clever, btw! To "invert" the result, you can also use the != "not equal" operator, which is easier to read.

func isOdd(i: Int) -> Bool {
  return i % 2 != 0
}

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.

Make sure to use the filter function instead of map, as stated above.

let oddNumbers = numbers.filter(isOdd)

Hope that helps!

Thank you! That makes a lot more sense.