Swift 3 - 如何将回调函数定义为参数

时间:2016-12-11 20:19:43

标签: swift function callback alamofire

希望使用Alamofire创建全局http请求功能/扩展名

function Request(requestPath:String, requestParams:Any, onComplate:Void) {
 // stuff here, when async request complate i want to call onComplate function
 // like C# method.Invoke() or func.Invoke()
}

3 个答案:

答案 0 :(得分:6)

您可以将闭包(函数)作为参数传递

swift
func request(requestPath:String, requestParams:Any, callback:((Result) -> Void)) { 
    ... 
}

Result将是您的回复类型。

答案 1 :(得分:3)

感谢您的回复,但最终解决方案

class HttpRequest<Request, Response>
{
    private var serviceBase:String = "http://192.168.1.1/api";
    func request(path:String, model: Request, success: @escaping((_ response: [Response]?) -> ()), failure: @escaping ((_ error:String) -> ()) {
         // code here..
    }
}

答案 2 :(得分:0)