Reputation: 2002
I have multiple var
Now I want my var totalScore to be = my other var added
here's my code
var section1score: Int = 0
var section2score: Int = 0
var section3score: Int = 0
var totalScore: Int = section1score + section2score + section3score
This code is not working... in var totalScore it's telling me that ViewController does not have a member named section1Score... and stops there
What am I doing wrong?
thanks !
Upvotes: 1
Views: 192
Reputation: 972
Try this
var section1score: Int!
var section2score: Int!
var section3score: Int!
var totalScore: Int!
override func viewDidLoad() {
super.viewDidLoad()
section1score = 0
section2score = 0
section3score = 0
totalScore = section1score + section2score + section3score
println(totalScore)
}
Upvotes: 1
Reputation: 9590
Is this code in a function? You cannot instance variables until init() has been completed. So if they are in a function this should work.
func test() {
var section1score: Int = 0
var section2score: Int = 0
var section3score: Int = 0
var totalScore: Int = section1score + section2score + section3score
}
Or if they need to be instance variables:
var section1score: Int = 0
var section2score: Int = 0
var section3score: Int = 0
var totalScore: Int = 0
init() {
totalScore = section1score + section2score + section3score
}
Upvotes: 1
Reputation: 12324
You can write totalScore
as a computed property so that it will always be the sum of the other 3 properties.
var totalScore: Int {
get {
return section1score + section2score + section3score
}
}
Upvotes: 4