-1

I'm trying to return JSON from function, for this I do:

func getAllItems() -> JSON {
    Alamofire.request(.GET, Links.sharedInstance.getAllItems, encoding: .JSON).validate().responseJSON { (response) in
        do {
            let json = JSON(data: response.data!)

            return json
        }
    }
}

but it gives me the next error:

Unexpected non-void return value in void function

How can I fix that? I've tried with a local variable inside of func, but in that case I got nil.

Any tips?

Doe
  • 431
  • 1
  • 8
  • 16
  • you use the return statement in the response area, not in your function area. declare a var in your function as var ret : JSON! replace 'return json' with 'ret = json' and afterwards 'return re', outside the response area – Luca Nicoletti Aug 03 '16 at 11:02
  • 1
    @LucaNicoletti No. You can't return from a closure. OP should use a callback. – Eric Aya Aug 03 '16 at 11:03
  • @EricD I did not say to return from a closure, I told him to assign a value to a var in the closure, and return it afterwards, but it would cause a null value to be returned if the response is not fast enough, you're tight, better use a callback – Luca Nicoletti Aug 03 '16 at 11:05
  • Have a look at the top [alamofire] questions. This has been asked and answered repeatedly. The Alamofire readme *explicitly* mentions the asynchronous response handling. – Martin R Aug 03 '16 at 11:05
  • @LucaNicoletti You're still very wrong. There's no "better use a callback", there's just "use a callback" in this case. If OP does what you say in your comment they won't ever get their data. – Eric Aya Aug 03 '16 at 11:08
  • 1
    Better duplicate target: http://stackoverflow.com/questions/27390656/how-to-return-value-from-alamofire – Eric Aya Aug 03 '16 at 11:17

1 Answers1

0

You should use completion handler like this:

func getAllItems(completion:(json: JSON?) -> (Void)) {
        Alamofire.request(.GET, Links.sharedInstance.getAllItems, encoding: .JSON).validate().responseJSON { (response) in
            do {
                let json = JSON(data: response.data!)

                completion(json)
            }
        }
    }
Muzahid
  • 5,072
  • 2
  • 24
  • 42