2016-05-29 46 views
-2

我正在做一些快速的Web服務。我正在使用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

查看['guard'語句](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Statements.html#//apple_ref/doc/uid/TP40014097 -CH33-ID434);) – Hamish

+2

您應該可以在http://codereview.stackexchange.com/上提出這個問題, – kye

+0

謝謝,我知道警衛聲明:)。你有一個想法,如果我可以使用衛兵梳理可選的綁定和調用功能, (當試圖解析json並綁定「數據」時,請參閱我的示例) – samir

回答

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)) 
.... 
.... 

如果讓語句可以與逗號鏈,如errordata以上。 同樣可以與警衛完成。