1

I am trying to use nested functions in my Swift Program.

func test()->Bool{
    func test1()->Bool{
        return true
    }

    func test2()->Bool{
        return true
    }

    func test3()->Bool{
        return true
    }
    return test1 && test2 && test3
 }

Its giving me some error! But if i try to

return test1

Its working fine.

Please explain why its giving me error on applying operators in nested function.

2 Answers 2

3

There are two approaches to nested functions/closures:

As you have it:

func test() -> Bool {
    func test1() -> Bool {
        return true
    }

    func test2() -> Bool {
        return true
    }

    func test3() -> Bool {
        return true
    }
    return test1() && test2() && test3()
}

Or saving it to closures and calling them:

func test() -> Bool {
    let test1 = { () -> Bool in
        return true
    }

    let test2 = { () -> Bool in
        return true
    }

    let test3 = { () -> Bool in
        return true
    }

    return test1() && test2() && test3()
}

The difference is really small and it comes down to your own preference but straight from documentation:

Nested functions are closures that have a name and can capture values from their enclosing function.

and

Closure expressions are unnamed closures written in a lightweight syntax that can capture values from their surrounding context.

Either way, both cases have to be called with () at the end of the name to perform their action, otherwise you're returning a function and not its evaluation. Your return test1 would be only valid in this case:

func test() -> (() -> Bool) {
    func test1() -> Bool {
        return true
    }

    return test1
}

where your function's return type is a function that returns Bool after you evaluate it. You want to evaluate though and return the Bool value combined with logical AND statements. Thus, you have to evaluate each function to get each function's Bool value to combine it and return the final value.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Michal for such elaborate answer!
@MinkeshJain just trying to also explain what is going on, not just blindly giving hotfix :)
@MinkeshJain don't forget to mark the answer that helped you as accepted. If your problem hasn't been solved yet, feel free to ask.
0

return test1 should fail as well, unless you have a test1 property in your class. It seems you are simply forgetting to call these as functions.

return test1() && test2() && test3() will work just fine.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.