我正在快速处理网络服务。我正在使用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))
}
}
}
}
}
答案 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语句可以与逗号链接在一起,就像上面的error
和data
一样。
警卫也可以这样做。