Theodore Haden
Theodore Haden

Reputation: 253

Return from a Function within a Closure

Why is it that in case 1, my function returns with ["reached end": "reached end"] not the value of the response dictionary? How can I make it return with the value of responseDictionary?

Background: HelperClass.doMath takes a number and has a completion block that returns a dictionary

func handleTask(task: [String: AnyObject]) -> AnyObject {
    switch task {
    case 1:
        if let bigNumber = task[bigNumberKey] as? NSNumber {
            HelperClass.doMath(bigNumber, replyBlock: {(responseDictionary: [NSObject: AnyObject]!) -> Void in
                return [responseDictionary]
            })
        }
    case 2:
        return 2
    case 3:
        return 3
    default:
        break
    }

    return ["reached end": "reached end"]
}

Upvotes: 2

Views: 1153

Answers (1)

Marcus Rossel
Marcus Rossel

Reputation: 3258

This should work:

func handleTask(task: [String: AnyObject]) -> AnyObject {
    switch task {
    case 1:
        if let bigNumber = task[bigNumberKey] as? NSNumber {
            return HelperClass.doMath(bigNumber, replyBlock: {(responseDictionary: [NSObject: AnyObject]!) -> Void in
                return [responseDictionary]
            })
        }
    case 2:
        return 2
    case 3:
        return 3
    default:
        break
    }

    return ["reached end": "reached end"]
}

Your closure replyBlock is being passed to the doMath method of HelperClass, and being used there for some purpose. It is executed in the scope of your handleTask function. Therefore return [responseDictionary] brings you back to the scope of your case 1, and doesn't cause handleTask to return anything.
What you're trying to do though (I assume) is return the result of this function. This can be achieved by simply adding a return in front of the method-call, which will in turn return any result doMath yields.

Upvotes: 1

Related Questions