0

I don't understand why the following doesn't work in Swift:

class SomeClass {
    var foo = 1
    var bar = self.foo + 1
}

and what's the way around it?

1 Answer 1

1

It doesn't work because you cannot use self in that scope to define default values for properties. I believe it is due to the fact that you cannot use self before the object is properly initialized. You could use an explicit initializer instead.

class SomeClass {
    var foo: Int
    var bar: Int

    init() {
        self.foo = 1
        self.bar = self.foo + 1
    }
}

You can, however, access static members.

class SomeClass {
    static let initialValue = 1
    var foo = initialValue
    var bar = initialValue + 1
}
Sign up to request clarification or add additional context in comments.

1 Comment

Got it, thanks for the explanation! Strange, but I get it.

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.