Lucas
Lucas

Reputation: 776

how to use the return value in a completion handler?

I'm trying to understand better the closures in swift and I've tried to create a silly function with a completion handler that returns a value but this value goes nowhere...

here's what I did..

func productToString(num: Int,num2: Int,completion: (Int)->String){

    let result = num * num2

    completion(result)
}




let numberToString = productToString(num: 3, num2: 6) { (res) -> String in

    return "string:\(res)"

}


print(numberToString) // print statement prints ()

when I tried to save this return value in a variable it returned just a pair of curvy brackets.

how should I use this return value?

Upvotes: 2

Views: 6215

Answers (1)

Keiwan
Keiwan

Reputation: 8301

You're returning the value into the productToString function but not doing anything else with it.

func productToString(num: Int,num2: Int,completion: (Int)->String){

    let result = num * num2

    completion(result) // <--- Your return value ends up here
}

If you want to print the result you have to return it again out of the productToString function.

func productToString(num: Int,num2: Int,completion: (Int)->String) -> String {

    let result = num * num2

    return completion(result)
}

Sidenote: The empty brackets that are printed are an empty tuple which is equivalent to Void in Swift.

Upvotes: 4

Related Questions