Sergio Bost
Sergio Bost

Reputation: 3249

How to capture the return value of a closure

I know that closures capture the values in a given environment. That is not my question. My question is how do I capture the return value of a closure. For example if I use a closure as a parameter like:

  func myClosure(yourAge x: Int, completion: (Int) -> String) {
    if x == 4 {
        completion(x)
    }
}

then say:

    let answer = myClosure(yourAge: 4) { x in
    return "You're just a baby"
}

The warning is:

Constant 'answer' inferred to have type '()', which may be unexpected

And I understand that warning. Pretty much answer will not be an answer at all. It will be Void or ()

Now if I make the entire function return a String such as:

   func myClosure(yourAge x: Int, completion: (Int) -> String) -> String {
    completion(x)
}

Then I can of course capture the result in a property:

    let answer = myClosure(yourAge: 4) { x in
   
    if x < 10 { return "You're just a baby"}
    else {
        return "You can play the game"
    }
}

And maybe I just answered my own question here but is there no simple way to place the return value of a closure into a property or I am using this in an unintended way?

Upvotes: 1

Views: 1071

Answers (1)

Paulo Fierro
Paulo Fierro

Reputation: 603

If you wanted to do this purely with a closure (and not a function that accepts a closure), you could do something like:

let myClosure: (Int) -> String = { age in
    if age < 10 {
        return "You're just a baby"
    }
    else {
        return "You can play the game"
    }
}

let answer = myClosure(4) // "You're just a baby"

Upvotes: 2

Related Questions