0

In my iOS app written in Swift I have an Error class, which extends from NSError.

class MyError: NSError {

    class var ErrorDomain: String { return "com.domain.app.error" }
    class var ErrorCode: Int { return 0 }

    init(data: [String: AnyObject]) {
        let userInfo: [String: AnyObject] = [
            "data": data
        ]
        super.init(
            domain: self.classForCoder.ErrorDomain,
            code: self.classForCoder.ErrorCode,
            userInfo: userInfo
        )
    }

    [...]

}

I have also other error classes that extends from the one above:

class MyError2: MyError {

    override class var ErrorDomain: String { return "com.domain.app.error2" }
    override class var ErrorCode: Int { return 0 }

    [...]

}

That way I can use init from MyError class, and have custom domains and codes for subclassed error objects.

It was working well on Xcode 6.0.1. The problem is, it won't compile in Xcode 6.1. I get this compiler error in MyError class in lines:

[...]
domain: self.classForCoder.ErrorDomain,
code: self.classForCoder.ErrorCode,
[...]

Use of property 'classForCoder' in base object before super.init initializes it

Is it possible to get Class object in init before calling super.init? I know it could sound strange, but I think my example shows why I need it.

Darrarski
  • 3,882
  • 6
  • 37
  • 59

1 Answers1

0

You have to initialize all instance properties before calling super.init().

But since you are passing values of type properties you could simply write

super.init(
        domain: MyError.ErrorDomain,
        code: MyError.ErrorCode,
        userInfo: userInfo
    )
marcusficner
  • 915
  • 8
  • 13
  • That obviously will work. Unfortunately, when init will be called on `MyError2`, new object will have domain and code from `MyError` instead of `MyError2` class. Am I right? – Darrarski Oct 20 '14 at 10:12
  • Yes, you're totally right. Sorry, haven't thought about that. – marcusficner Oct 20 '14 at 10:22