Gavin
Gavin

Reputation: 2834

Closure to return value to outerblock?

I would like my static function to return a bool as such static func search(email: String?) -> Bool

I tried to do the commented out part but it getting returned as the return value of the closure. How do I get it to return values to the outer calling function search(email: String?)

 static func search(email: String?){
        HTTPClient().apiQuery(.GET, endpoint: "user.jsn", params: ["user":["email": email!]], handler: {
            response in
            print(response)
            switch response.result {
            case .Success(let successJSON):
                let successResponse = successJSON as! Dictionary<String, AnyObject>
                if let error = successResponse["errors"] {
                    print(error)
                    // return false
                }
                // else { return true }

            case .Failure :
                print("Failure")
                // return false
            }
        })
    }

Upvotes: 0

Views: 85

Answers (2)

G&#252;rhan KODALAK
G&#252;rhan KODALAK

Reputation: 580

I'm not sure about static functions but you can use completionHandler like was Objective-C

https://stackoverflow.com/a/39643395/4320266

typealias successSearch = () -> Bool

func search(email: String?, isSuccess:successSearch){

}

something like this

Hope it helps.

Upvotes: 0

Greg
Greg

Reputation: 25459

You need to change your method signature to return a completion handler with the type you expecting and inside apiQoery just call it when you have the data:

static func search(email: String?, completion: (Dictionary<String, AnyObject>) -> ()){
    ....
    let successResponse = successJSON as! Dictionary<String, AnyObject>
    completion(successResponse)
    ....
}

You can call it like that:

YOURCLASSNAME.search(email: nil) {
    responce in
        // Use your dictionary here
}

In your case when method returns dictionary but it may returns error would be better to create object which can return both, for example enum Result it's quite popular. See this link for more details.

Upvotes: 4

Related Questions