如果让测试,请避免快速嵌套

时间:2016-05-29 18:38:53

标签: swift

我正在快速处理网络服务。我正在使用alamofire。代码正在运行,但我认为它不可读" (不是一个干净的代码)。你知道我如何优化这个吗?感谢

static func checkBookValidity(serialNumber: String, callBack: Result<Bool?> -> ()) {

      let router = Router.CheckBookLuggage(serialNumber: serialNumber)
      let request = Alamofire.request(router)
      request.validate()
      request.response { (request, response, data, error) in
         if let error = error {
            if error.code == NSURLErrorNotConnectedToInternet {
               callBack(.Failure(.NoConnection))
            }
            else {
               if let data = data {
                  do
                  {
                     if let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [String : AnyObject] {
                        let erroType = WSError.errorTypeWithJson(json, httpErroCode: error.code)
                        callBack(.Failure(erroType))
                     }
                  } catch {
                     callBack(.Failure(.ServerError))
                  }
               }
               else {
                  callBack(.Failure(.ServerError))
               }
            }
         }
         else {
            if let data = data {
               do
               {
                  if let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [String : AnyObject] {
                     if let resultDic = json["result"] as? [String:AnyObject], let exists = resultDic["exists"] as? Bool {
                        if exists {
                           if let owner = resultDic["email"] as? String {
                              // ...
                           }
                        }
                        else {
                           callBack(.Success(false))
                        }
                     }
                  }
               } catch {
                  callBack(.Failure(.ServerError))

               }
            }
         }
      }
   }

1 个答案:

答案 0 :(得分:2)

试试这个

if let error = error, data = data {
    do {
        if let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [String : AnyObject] {
            let erroType = WSError.errorTypeWithJson(json, httpErroCode: error.code)
            callBack(.Failure(erroType))
....
....

如果let语句可以与逗号链接在一起,就像上面的errordata一样。 警卫也可以这样做。