ios - Using a Swift closure to capture a variable -
i have bit of code , errors out because when use foo in return statement it's outside of scope of function. know (i think know) need use closure capture variable can't figure out how that. using alamofire & swiftyjson. great! thanks!
func getplayerid(named: string) -> string { alamofire.request(.get, "url", headers: headers) .responsejson { response in let json = json.self(response.result.value!) var index = 0; index < json.count; index++ { if json[index]["name"].stringvalue == named { var foo = json[index]["foo"].stringvalue } // if statement end } // loop end } // alamofire request end // return statement getplayerid function return foo } // getplayerid function end } // player struct end
the basic idea getplayerid
should not return anything, rather should have parameter closure, , once retrieve value want "return", call closure using value parameter.
but, i'd suggest sorts of other refinements here:
- build array of strings , return that
- check see if
result
.failure
because have no control on various server/network issues may arise - change closure detect , report errors
but illustrates basic idea:
personally, i'd (a) make string
parameter completionhandler
optional; (b) add optional error parameter; , (c) add error handling getplayerid
:
func getplayerid(completionhandler: ([string]?, errortype?) -> void) { alamofire.request(.get, "url", headers: headers) .responsejson { request, response, result in switch (result) { case .success(let value): let json = json.self(value) // variable hold of results var strings = [string]() // populate array of strings var index = 0; index < json.count; index++ { if json[index]["name"].stringvalue == named { strings.append(json[index]["foo"].stringvalue) } } // call completion handler strings completionhandler(strings, nil) case .failure(_, let error): completionhandler(nil, error) } } }
and then, when want call it:
getplayerid() { strings, error in // use `strings` here } // not here
Comments
Post a Comment