我正在尝试检查statusCode是否等于2xx,但是我不太确定如何为该类型的错误处理创建此正则表达式代码。这是我的代码,目前有一个从头文件中检索statusCode的变量?
func SignUpWithPassword(email: String, password: String, delegate: CreateUserDelegate) {
testProvider.request(.SignIn(email, password), completion: { result in
switch result {
case let .Success(response):
let statusCode = response.statusCode
case let .Failure(error):
print(error)
let description = "Error! Please try again!"
delegate.CreateUser(didError: description)
}
})
delegate.CreateUser(didSucceed: SignUpUser(email: email, password: password))
}
答案 0 :(得分:0)
我相信NSHTTPURLResponse状态代码是一个Int。 你应该能够在你的分支逻辑中使用远程表达式:
switch response.statusCode
{
case 200 ... 299 :
print("Success")
default:
print("Failure")
}
答案 1 :(得分:0)
我正在使用这个枚举:
enum HTTPStatusCodeGroup: Int {
case Info = 100
case Success = 200
case Redirect = 300
case Client = 400
case Server = 500
case Unknown = 999
init(code: Int) {
switch code {
case 100...199: self = .Info
case 200...299: self = .Success
case 300...399: self = .Redirect
case 400...499: self = .Client
case 500...599: self = .Server
default: self = .Unknown
}
}
}
答案 2 :(得分:-1)
在Swift中,我创建了自己的Regax类。
// Custom Regex class
class Regex {
let internalExpression: NSRegularExpression
let pattern: String
init(_ pattern: String) {
self.pattern = pattern
do {
self.internalExpression = try NSRegularExpression(pattern: self.pattern, options: .CaseInsensitive)
} catch _ {
self.internalExpression = NSRegularExpression.init();
}
}
func test(input: String) -> Bool {
let matches = self.internalExpression.matchesInString(input, options: .WithTransparentBounds, range: NSMakeRange(0, input.characters.count)) as Array<NSTextCheckingResult>
return matches.count > 0
}
}
// Override operator
infix operator =~ {}
func =~ (input: NSInteger, pattern: String) -> Int {
return (Regex(pattern).test(String(input))) ? input : -1;
}
// Example add it viewDidLoad method
let statusCode = 200
switch statusCode
{
case statusCode =~ "2[0-9][0-9]" :
print("2[0-9][0-9] Success")
break
case statusCode =~ "3[0-9][0-9]" :
print("3[0-9][0-9] Success")
break
case statusCode =~ "4[0-9][0-9]" :
print("4[0-9][0-9] Success")
break
case statusCode =~ "5[0-9][0-9]" :
print("5[0-9][0-9] Success")
break
default:
print("Failure")
}