我正在尝试使用range运算符找出一种替代方法来执行类似的操作。

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}

在Swift中有可能吗?

最佳答案

随你心意:

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}

关于swift - 我可以在Swift的保护声明中使用范围运算符吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43967229/

10-12 03:05