Greg R
Greg R

Reputation: 1691

Referencing another variable in a global variable in swift

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?

Upvotes: 0

Views: 26

Answers (1)

hennes
hennes

Reputation: 9352

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
}

Upvotes: 1

Related Questions