2016-04-27 27 views
1

我在Swift中發出一個url請求,並希望打印一個有意義的錯誤,包括響應代碼,如果它們是一個。我試圖用盡可能少的代碼行來做到這一點。我在XCode中收到的錯誤如下:Variable declared in 'guard' condition not usable in its body在聲明的主體中使用警戒條件

如何執行以下操作而不將代碼膨脹至更多行,是否有可能?

//check to see if we got a valid response code 
    guard let resCode = (response as? NSHTTPURLResponse)?.statusCode where resCode == 200 else { 
     return NSError(domain: "Error with request", code: 1, userInfo: [NSLocalizedDescriptionKey: "Recieved the following status code: \(resCode)"]) 
    } 

錯誤發生時我嘗試使用保護聲明的正文中的變量resCode

+0

只使用'(response as?NSHTTPURLResponse)?. statusCode'而不是var –

+0

如果'response'旁邊有一個'error'參數,如果沒有錯誤,'response'很可能是非'nil'返回並且如果您發送了HTTP請求,則響應也很可能是HTTP響應。 – vadian

回答

5

由於錯誤狀態,您不能使用您在guard語句正文內的guard語句中綁定的變量。只有在沒有進入警戒體的情況下,變量纔會受到約束。您還沒有病例之間的區別在那裏你的反應是零,您的狀態代碼不是200

你應該打破報表分爲兩個不同的檢查:

guard let httpResponse = response as? NSHTTPURLResponse else { 
    return NSError(domain: "Error with request", code: 1, userInfo: [NSLocalizedDescriptionKey: "Invalid response: \(response)"]) 
} 

guard httpResponse.statusCode == 200 else { 
    return NSError(domain: "Error with request", code: 1, userInfo: [NSLocalizedDescriptionKey: "Recieved the following status code: \(httpResponse.statusCode)"]) 
} 

不要試圖以可讀性或正確性爲代價最小化代碼行數。