class Plane { enum Emergency: ErrorType { case NoFuel case EngineFailure(reason: String) case DamagedWing } var fuelInKilograms: Int //...未显示init和其他方法 func fly() throws { // ... if fuelInKilograms <= 0 { // 呃哦 throw Emergency.NoFuel } } }
在客户端类中:
let airforceOne = Plane() do { try airforceOne.fly() } catch let emergency asPlane.Emergency{ switch emergency { case .NoFuel: // 致电最近的机场紧急降落 case .EngineFailure(let reason): print(reason) // 让机械师知道原因 case .DamagedWing: // 评估损失并确定总统是否可以做到 } }