我想查看HTTPURLResponse statusCode是否以2开头以指示成功。看看它是否在200到299之间(含200和299)是否更有意义?还是Swift有内置函数来查看HTTP状态代码是否代表成功?
也就是说,
var statusCode: Int = ..
以下哪个表达式是首选?
let success = String(statusCode).prefix(1) == "2"
let success = statusCode < 300 && statusCode >= 200
相关文档阅读
The first digit of the Status-Code defines the class of response. The
last two digits do not have any categorization role. There are 5
values for the first digit:
- 1xx: Informational - Request received, continuing process
- 2xx: Success - The action was successfully received,
understood, and accepted
- 3xx: Redirection - Further action must be taken in order to
complete the request
- 4xx: Client Error - The request contains bad syntax or cannot
be fulfilled
- 5xx: Server Error - The server failed to fulfill an apparently
valid request
答案 0 :(得分:2)
您是正确的,任何介于200到299(含)之间的值都表示成功。
但是,这还不完整。 3XX响应可能意味着您还不知道请求是否成功,并且您需要按照重定向来确定真实状态。
303重定向可以导致返回404或200 OK的URI。