Reputation: 1691
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
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