1

Have a simple question on Swift. I have a simple base class Base and a child class ABase:

class Base {
    var test1:Int

    init(forTest test1:Int) {
        self.test1 = test1
    }
}

class ABase : Base {
    var test3:Int

    init(forAnother test3:Int) {
        **super.init(forTest: test3)**
        self.test3 = test3
    }
}

I get a compiler error at the super.init(forTest: test3) line in my init call in ABase. The error is:

Property 'self.test3' no initialized at super.init call.

I'm trying to understand why I can't init an object with an uninitialized var in Swift?

1 Answer 1

2

Swift has a two-phase init, in which you need to initialize all of your members before doing anything else.

init(forAnother test3:Int) {
    self.test3 = test3
    super.init(forTest: test3)
}

More info here:

https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/Initialization.html

Search for two-phase init on the page.

If you needed to call super.init() (for example, if test3 depended on what it did), you could give an initial value to test3 in its declaration.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.