斯威夫特:得到暧昧的表达"当尝试将元组传递给回调函数时

时间:2015-01-15 10:43:43

标签: ios swift alamofire

我有这个类用于根据我的后端验证用户。

class BackendService {


class func performLogin(#email: String, password: String, success:((res: NSHTTPURLResponse, json: JSON, statusCode: HTTPStatus))->(), failure: (NSError)->()) {

    let loginURL = baseURL + "/login"
    let parameters = ["email": email, "password": password]

    Alamofire.request(.POST, loginURL, parameters: parameters).responseJSON { (req, res, json, err) in

        if(err != nil) {
            let response = (error: err!)
            failure(response)
        }
        else {


            if let httpStatus = HTTPStatus(rawValue: res!.statusCode) {
                let response = (res: res, json: JSON(json!) , statusCode: httpStatus)
                success(response)
            }
        }
    }

}

success(response)我得到Type of expression is ambiguous without more context。有任何想法吗?

写这门课有没有更好,更快捷的方式?

1 个答案:

答案 0 :(得分:6)

它没有编译的原因是你在成功元组声明周围有一组额外的括号。如果你删除它们,那么它将编译。这是您的函数的更新版本,尽可能少的编译更改。

  

您需要确保在某处定义baseURL

class func performLogin(#email: String, password: String, success:(res: NSHTTPURLResponse, json: JSON, statusCode: HTTPStatus)->(), failure: (NSError)->()) {

    let loginURL = baseURL + "/login"
    let parameters = ["email": email, "password": password]

    Alamofire.request(.POST, loginURL, parameters: parameters).responseJSON { (req, res, json, err) in

        if (err != nil) {
            let response = (error: err!)
            failure(response)
        }
        else {
            if let httpStatus = HTTPStatus(rawValue: res!.statusCode) {
                let response = (res: res!, json: JSON(json!), statusCode: httpStatus)
                success(response)
            }
        }
    }
}

这是原始功能的更新版本,当然更清晰,但还不完全安全。一个好的经验法则是感叹号越多,风险就越大。

typealias LoginSuccessHandler = (NSHTTPURLResponse, JSON, HTTPStatus) -> Void
typealias LoginFailureHandler = (NSError) -> Void

class func performLogin(#email: String, password: String, success: LoginSuccessHandler?, failure: LoginFailureHandler?) {
    let loginURL = baseURL + "/login"
    let parameters = ["email": email, "password": password]

    Alamofire.request(.POST, loginURL, parameters: parameters).responseJSON { request, response, json, error in
        if let error = error {
            failure?(error)
        } else {
            if let httpStatus = HTTPStatus(rawValue: response!.statusCode) {
                success?(response!, JSON(json!), httpStatus)
            }
        }
    }
}

你应该真正了解@mattt在Alamofire.Request类中内置的非常好的验证逻辑。这样您就可以完全取消对HTTPStatus枚举的需求。

  • public func validate() -> Self
  • public func validate(contentType array: [String]) -> Self
  • public func validate(statusCode array: [Int]) -> Self
  • public func validate(statusCode range: Range<Int>) -> Self
  • public func validate(validation: Validation) -> Self