Swift var 添加不起作用
Swift var addition does not work
我有多个变量
现在我希望我的 var totalScore = 我添加的其他 var
这是我的代码
var section1score: Int = 0
var section2score: Int = 0
var section3score: Int = 0
var totalScore: Int = section1score + section2score + section3score
此代码无效...在 var totalScore 中它告诉我 ViewController 没有名为 section1Score 的成员...并停在那里
我做错了什么?
谢谢!
您可以将 totalScore
写成计算的 属性,这样它将始终是其他 3 个属性的总和。
var totalScore: Int {
get {
return section1score + section2score + section3score
}
}
这段代码在函数中吗?在 init() 完成之前,您不能实例化变量。所以如果他们在一个函数中,这应该可以工作。
func test() {
var section1score: Int = 0
var section2score: Int = 0
var section3score: Int = 0
var totalScore: Int = section1score + section2score + section3score
}
或者如果它们需要是实例变量:
var section1score: Int = 0
var section2score: Int = 0
var section3score: Int = 0
var totalScore: Int = 0
init() {
totalScore = section1score + section2score + section3score
}
试试这个
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)
}
我有多个变量
现在我希望我的 var totalScore = 我添加的其他 var
这是我的代码
var section1score: Int = 0
var section2score: Int = 0
var section3score: Int = 0
var totalScore: Int = section1score + section2score + section3score
此代码无效...在 var totalScore 中它告诉我 ViewController 没有名为 section1Score 的成员...并停在那里
我做错了什么?
谢谢!
您可以将 totalScore
写成计算的 属性,这样它将始终是其他 3 个属性的总和。
var totalScore: Int {
get {
return section1score + section2score + section3score
}
}
这段代码在函数中吗?在 init() 完成之前,您不能实例化变量。所以如果他们在一个函数中,这应该可以工作。
func test() {
var section1score: Int = 0
var section2score: Int = 0
var section3score: Int = 0
var totalScore: Int = section1score + section2score + section3score
}
或者如果它们需要是实例变量:
var section1score: Int = 0
var section2score: Int = 0
var section3score: Int = 0
var totalScore: Int = 0
init() {
totalScore = section1score + section2score + section3score
}
试试这个
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)
}