您的位置:首页 > 移动开发 > Swift

在方法中使用闭包

2016-04-13 13:30 337 查看
以网络请求为例

class func httpRequest( // 类方法
type: RequestMethodType,
url:String,
params: NSDictionary,
success: ((response: AnyObject)->Void), // 成功的闭包,参数是response,没有返回值,Void大写
failure: ((error: NSError)->Void)) {

let manager = AFHTTPRequestOperationManager()

switch type {
case .Get:

manager.GET(url, parameters: params, success: { (operation: AFHTTPRequestOperation!,  responseObject: AnyObject!) in

success(response: responseObject) // 响应数据

}, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in

failure(error: error) // 失败信息
})
break

case .Post:
manager.POST(url, parameters: params, success: { (operation: AFHTTPRequestOperation!,  responseObject: AnyObject!) in
success(response: responseObject)

}, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in
failure(error: error)
})
break

}
}


使用:

一个闭包,传递结果

func getUser(userId: String, completion:((User?) -> Void)) { // 不带参数
let user = User()

let parameters: NSDictionary = [
"search_user": userId
];

// 使用网络请求
HttpTool.httpRequest(RequestMethodType.Get, url: kHttpUserInfo, params: parameters, success: { (response) in
let arr = response as! NSArray
if arr.count >= 1 {
let dic = arr[0] as! NSDictionary
user.userId = dic["user_id"] as! String
user.portrait = dic["portrait"] as! String
user.signature = dic["signature"] as! String
user.username = dic["username"] as! String
user.sex = dic["sex"] as! String
completion(user) // 不带参数。请求完成,传递user
}
}) { (error) in
completion(nil) // 如果错误,设置为nil
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  闭包 swift