Swift 在方法中使用闭包

以网络请求为例

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 在方法中使用闭包)