2017-05-14 46 views
4

我想找出一個替代方法來做這樣的事情,使用範圍運算符。我可以在Swift的guard語句中使用範圍運算符嗎?

guard let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode >= 200 && statusCode <= 299 else {return} 

也許是這樣的:

guard let statusCode = (response as? HTTPURLResponse)?.statusCode where (200...299).contains(statusCode) else {return} 

guard let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode case 200...299 else {return} 

這是可能的斯威夫特?

+0

不錯的問題! – Fattie

+0

相關:[我可以使用範圍運算符與if語句在Swift?](http://stackoverflow.com/questions/24893110/can-i-use-the-range-operator-with-if-statement-in- swift) –

+2

switch語句中範圍的模式匹配由'〜='運算符定義。這是一個非常酷的功能,因爲這意味着您可以在switch語句中進行任何匹配,您可以使用'〜='手動執行。這也意味着您可以通過實現定製的'〜='操作符函數來擴展switch語句的功能。 – Alexander

回答

4

正如你喜歡:

guard 
    let statusCode = (response as? HTTPURLResponse)?.statusCode, 
    (200...299).contains(statusCode) else {return} 

或:

guard 
    let statusCode = (response as? HTTPURLResponse)?.statusCode, 
    case 200...299 = statusCode else {return} 

或:

guard 
    let statusCode = (response as? HTTPURLResponse)?.statusCode, 
    200...299 ~= statusCode else {return} 
+0

謝謝!有趣的是,所有回覆的人都將警戒聲明放在單獨的一行上。這是一個慣例嗎?我以前沒有見過。 –

+1

@KeithGrout,我不知道這是不是流行的慣例。但在關鍵字「guard」之後放行換行表明它有多個條件。 – OOPer

2

這裏是一個不可能性的解決方案

guard 
    let statusCode = (response as? HTTPURLResponse)?.statusCode, 
    200...299 ~= statusCode 
    else { return } 
1

只是針對不同的解決方案,您還可以使用:

guard 
    let statusCode = (response as? HTTPURLResponse)?.statusCode, 
    statusCode/100 == 2 
else { 
    return 
} 
相關問題