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

2nd challenge :( need your help

guys i need your help in the challenge :

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 wrote it like this :

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

func isOdd ( i : Int) -> Bool { var found = (false) for me in numbers { if me % 2 != 0 { found = false } else { found = true } } return found }

let ifOdd = isOdd

let oddNumbers = numbers.filter(isOdd)

and i can't get odd numbers :(

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

func isOdd ( i : Int) -> Bool {
    var found = (false)
    for me in numbers {
        if me % 2 != 0 {
            found = false
        } else {
            found = true
        }
    }
    return found
}

let ifOdd = isOdd

let oddNumbers = numbers.filter(isOdd)

1 Answer

Steven Deutsch
Steven Deutsch
21,046 Points

Hey NOUR A ALGHAMDI,

You first need to create a function that takes an Int as its parameter and returns a Boolean based on whether the Int passed in is true or false. You don't need to create a variable to store the Bool. You also don't need a for loop inside of your function, you will be using the filter method to iterate through the array and then pass filter your function as an argument. Your function is being used to tell filter what conditions to filter by.

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

// Enter your code below

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

/* After we set up our isOdd function
we call filter on the numbers array
and pass it our isOdd function.

We assign the results to a constant
called oddNumbers. */

let oddNumbers = numbers.filter(isOdd)

Hope this helps! Good Luck!

thanks Steven Deutsch :) i'm grateful for your help :)