2017-05-14 50 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 
} 
相关问题