斯威夫特枚举评价

问题描述:

使用Alamofire我们试图确定是否错误是某种作为一个“嵌套” AFError枚举表示的错误(响应代码499)的:斯威夫特枚举评价

if response.result.isFailure { 
     if let aferror = error as? AFError { 
      //THIS LINE FAILS 
      if (aferror == AFError.responseValidationFailed(reason: AFError.ResponseValidationFailureReason.unacceptableStatusCode(code: 499))) { 
       .... 
      } 
     }    
    } 

但是,这导致编译器错误:

Binary operator '==' cannot be applied to two 'AFError' operands

你怎么能这样做?

那么,你可以尝试扩大AFEError符合Equatable为了使用==,但你可能使用switch和模式匹配更好:

switch aferror { 
    case .responseValidationFailed(let reason) : 
     switch reason { 
      case AFError.ResponseValidationFailureReason.unacceptableStatusCode(let code): 
       if code == 499 { print("do something here") } 
      default: 
       print("You should handle all inner cases") 
     { 
    default: 
     print("Handle other AFError cases") 
} 

这是最好的语法,以确保(并获得编译器可以帮助您确保)处理所有可能的错误情况和原因。如果你只是想在你的榜样,以解决一个案例一样,你可以使用新if case语法,就像这样:

if case .responseValidationFailed(let reason) = aferror, case AFError.ResponseValidationFailureReason.unacceptableStatusCode(let code) = reason, code == 499 { 
    print("Your code for this case here") 
} 

正如我指出的here,你不能,默认情况下,适用平等(== )运算符在作为关联值的枚举的情况下(在其案例的的任何之间);但还有很多其他方法可以确定这是否是所需的情况(并且,如果存在相关的值,则可以了解相关联的值可能是多少)。

+0

如果使枚举类型符合“Equatable”,则可以应用'=='枚举具有关联值的情况。你只是不要免费获得它。 –

+1

好吧;我将补充一点。另请参阅我在这个问题上的bug报告:https://bugs.swift.org/browse/SR-2900 - 正如乔丹罗斯所说,Swift未能“综合Equatable”,这是一个更多一般投诉。 – matt

+0

对于Swift,+1会自动将枚举与相关的Equatable类型相符/合成,以便自己进行Equatable!也许在Swift 4中... –