我'修复'之前的错误,但这样做最终让它说'变量'回答“在声明之前使用”,当我明确宣布它时。代码有什么问题?
if operation.text == "/" {
identifyVal()
var answer:Float = 0.0 // declared the value of answer
answer = round(Float(randomNumber)/Float(randomNumber2))
}
var answer:UInt32
if operation.text == "+" {
answer = randomNumber + randomNumber2 //nothing wrong
}
if operation.text == "-" {
identifyVal()
answer = randomNumber - randomNumber2
}
if operation.text == "x" {
answer = randomNumber * randomNumber2
}
secretAnsarrrrr.text = String(answer) //error
numA.text = String(Int(randomNumber))
numB.text = String(Int(randomNumber2))
代码的另一部分是:
if optionAnswer == 0 {
optionA.text = secretAnsarrrrr.text // nothing wrong
}
我该如何解决这个问题?
这是我放置UILabel'secretAnsarrrr'
的屏幕截图答案 0 :(得分:1)
只需以这种方式声明answer
:
var answer:UInt32?
你的错误将会解决。
<强>更新强>
var answer:Float = 0.0
if operation.text == "/" {
}
if operation.text == "+" {
}
if operation.text == "-" {
}
if operation.text == "x" {
}
secretAnsarrrrr.text = "\(answer)"
答案 1 :(得分:0)
在那部分:
var answer:UInt32
if operation.text == "+" {
answer = randomNumber + randomNumber2 //nothing wrong
}
if operation.text == "-" {
identifyVal()
answer = randomNumber - randomNumber2
}
if operation.text == "x" {
answer = randomNumber * randomNumber2
}
如果operation.text
不是+,则 - 或x answer
将为零。您有两个选项 - 是否设置初始值以回答:
var answer:UInt32 = 0
或者让它成为可选项并在之后解开它:
var answer:UInt32?
if operation.text == "+" {
answer = randomNumber + randomNumber2 //nothing wrong
}
if operation.text == "-" {
identifyVal()
answer = randomNumber - randomNumber2
}
if operation.text == "x" {
answer = randomNumber * randomNumber2
}
if let answer = answer
{
secretAnsarrrrr.text = String(answer) //error
}