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

Nesting function in another function - why is my code not working?

  1. User inputs an integer
  2. Determine whether it's positive or negative
  3. Return "This number is positive" or "This number is negative"

I've started by writing an evaluateIfPositive boolean function that determines whether it's positive, then using that function inside the announcePositiveOrNegative function.

func evaluateIfPositive(integer: Int) -> Bool {
    if integer < 0 {
        return false
    } else {
        return true
    }
}

func announcePositiveOrNegative(for userInput: Int) -> String {
    evaluateIfPositive(userInput) {
        if true {
            return "This number is positive"
        } else {
            return "This number is negative"
        }
    }
}

Error returned on this line:

evaluateIfPositive(userInput) {

"Extra argument in call"

What am I doing wrong?

2 Answers

Hi, Laurie. After you call evalutateIfPositive() you opened a block with {} this is why you get an error. You defined evalutateIfPositive to return a boolean value, so you should grab that value in a variable like so:

func evaluateIfPositive(integer: Int) -> Bool {
    if integer < 0 {
        return false
    } else {
        return true
    }
}

func announcePositiveOrNegative(for userInput: Int) -> String
{
    let result = evaluateIfPositive(integer: userInput)

    if result {
        return "This number is positive"
    } else {
        return "This number is negative"
    }
}

Also, note that you should type the argument label 'integer' when calling evaluteIfPositive() function.

The problem is the syntax, since your function returns a bool you check it like this

func evaluateIfPositive(integer: Int) -> Bool {
    if integer < 0 {
        return false
    } else {
        return true
    }
}

func announcePositiveOrNegative(for userInput: Int) -> String {
    if evaluateIfPositive(integer: userInput) == true {
        return "This number is positive"
    } else {
        return "This number is negative"
    }
}