SWIFT2:EXC_BAD_ACCESS向下转换符合ErrorType

时间:2015-10-10 16:51:29

标签: switch-statement swift2 exc-bad-access downcast

我有一个简单的Object层次结构:带有2个属性的RESTError(httpCode和message),以及它的4个子类。其中一个子类RESTBusinessError有两个额外的字段。

我在下面简化了我的代码,但在switch语句中使用了一个RESTError变量(实际上是一个RESTBusinessError)。每当我尝试访问子类的字段时,我都会有EXC_BAD_ACCESS。任何的想法 ?这看起来很明显,在调试区域,我可以看到我的所有变量都有预期的值。

我只有在RESTError符合协议ErrorType的情况下才会遇到此问题。

任何想法?enter image description here

    var tmpError:RESTError;
    tmpError=RESTBusinessError(httpCode: 422, message: "error", businessCode: "003", businessMessage: "error");

    switch tmpError {
        case is RESTAuthorisationError:print("AUTH Error");
        case let bError as RESTBusinessError:
            let s1=bError.httpCode;
            let s2=bError.message;
            let s3=bError.businessCode;    // <- This systematically fails.
            let s4=bError.businessMessage;
            print("OK \(s1) \(s2) \(s3) \(s4)");
        default: print("default");
    }

对象层次结构如下:

public class RESTError : ErrorType{
    var httpCode:Int
    var message:String

    init(httpCode:Int,message:String) {
        self.httpCode=httpCode;
        self.message=message;
    }
}

class RESTAuthorisationError : RESTError {}

class RESTServerError : RESTError {}

class RESTOtherError : RESTError {}

public class RESTBusinessError : RESTError {
    var businessCode:String
    var businessMessage:String

    init(httpCode:Int,message:String, businessCode:String, businessMessage:String) {
        self.businessCode=businessCode;
        self.businessMessage=businessMessage;
        super.init(httpCode: httpCode, message: message);
    }
}

1 个答案:

答案 0 :(得分:-1)

检查此示例

import Foundation

func f() {
    let queue = dispatch_queue_create("a", DISPATCH_QUEUE_CONCURRENT)
    var i: Int! = 0
    dispatch_async(queue) {
        i = nil
    }
    usleep(200000)
    print(i) // this is wrong
}
f() // debugger will stop here !!!!