2

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"]
}
8
  • 1
    When working with asynchronous code you have to use callbacks, not return. So your handleTask also needs a block analogous to replyBlock to call when you get responseDictionary
    – User
    Aug 5, 2015 at 19:04
  • Hmm - it is asynchronous actually. Aug 5, 2015 at 19:05
  • Is the closure executed synchronously or asynchronously? If it is synchronous, why do you use a closure? Aug 5, 2015 at 19:05
  • @lxx Sounds about right - How could I rewrite handleTask to do that? Aug 5, 2015 at 19:13
  • Your code has some really weird parts. Does it really compile? Your switch task works on dictionary, but you are checking for values 1, 2 and 3. 1, 2, or 3 are not a dictionary. Also, your replyBlock accepts dictionary and returns void, but you are attempting to return array of dictionaries [responseDictionary]. I think you should look into these things and make sure that the code is doing what you really want.
    – MirekE
    Aug 5, 2015 at 19:22

1 Answer 1

1

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.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.