Reputation: 3060
Why can I not perform operations with a variable or constant at the class level? Is this not allowed or is there a keyword I need to use to access them? Is this bad practice?
Controller:
class ViewController: UIViewController {
let one = 1
let two = 2
var sum = one + two
}
Error:
ViewController.Type does not have a member named 'one'
Upvotes: 1
Views: 242
Reputation: 42159
Class variables and constants must be static
, e.g., static let one = 1
.
Here it suffices for the two let
constants to be static
for them to be usable in initializing both class and instance variables. The following works for me:
class MyClass {
static let one = 1
static let two = 2
static var sum = one + two
var instanceProduct = one * two
}
MyClass.one
MyClass.sum
MyClass().instanceProduct
Note that in the above example you can do MyClass.sum = 5
. If you meant the sum to be constant as well, simply change it to static let sum = one + two
.
The requirement is that the constants you use outside of any functions and closures be declared static let
. The implication of this is that they are truly constant for the entire class. If you need instance-specific constants, you cannot use them outside of functions or closures (as you've noticed) – as a workaround for a variable sum
I would suggest a lazy
variable initialized by a closure:
class MyClass {
let one: Int // value given in `init`
let two = 2
lazy var sum: Int = { self.one + self.two }()
init(one: Int = 1) {
self.one = one
}
}
MyClass().sum // 3
MyClass(one: 2).sum // 4
Upvotes: 3
Reputation: 19966
Simple fix
override func viewDidLoad() {
super.viewDidLoad()
var result = one + two
}
Upvotes: 0