[英]How to inherit a function with closure in Swift
我已經在我的APIServices類中定義了此函數
typealias APIResponseOK = (data:NSDictionary, extra:NSDictionary) -> Void
typealias APIResponseError = (failure:Bool, code:NSString, message:NSString) -> Void
func getHttp(action:NSString, onResult:APIResponseOK, onError:APIResponseError) -> Void {
let strUrlRequst = String(format: "\(action)")
Alamofire.request(.GET, strUrlRequst).responseJSON { (responseData) -> Void in
if(responseData.result.error == nil){
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
print("Response \(swiftyJsonVar)")
onResult(data: swiftyJsonVar.dictionaryObject!, extra: swiftyJsonVar.dictionaryObject!);
}
}
else{
onError(failure: true, code: "OM_ERR", message: (responseData.result.error?.localizedDescription)!);
}
}
}
現在,我想在ViewController類中繼承此函數。 我嘗試的是波紋管。
apiServices.getHttp("Somename", onResult: (data:NSDictionary, extra:NSDictionary){
},
onError:(failure: Bool, code:NSString, message:NSString){
})
為什么我收到此錯誤。 請糾正我,我是新手
apiServices.getHttp("Somename", onResult:{ data: NSDictionary, extra: NSDictionary in
// some
}, onError:{ failure: Bool, code: NSString, message: NSString in
// some
})
您應該檢查所有Apple Swift文檔,而不要先使用它。 還有其他問題,例如,為什么要在Swift中使用NSString或NSDictionary。
更正您的函數聲明:
func getHttp(action:NSString, onResult:APIResponseOK, onError:APIResponseError) -> Void {
與:
func getHttp(action:NSString, onResult:APIResponseOK, onError:APIResponseError) {
之后,要調用此函數,您可以執行以下操作:
let myApiSuccess: APIResponseOK = {(data:NSDictionary?, extra:NSDictionary?) -> Void in
print ("Api Success : result is:\n \(data)")
// Here you can make whatever you want with your dictionaries
}
let myApiFailure: APIResponseError = {(failure:Bool?, code:NSString?, message:NSString?) -> Void in
print ("Api Failure : error is:\n \(message)")
// Here you can check the errors with your vars looking for failure, code and message
}
getHttp(action:NSString, onResult:APIResponseOK, onError:APIResponseError)
您可以在此答案中找到更多詳細信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.