已经声明的变量显示 'variable used before declaration'

Already declared variable shows 'variable used before declaration'

我 'fixed' 之前的一个错误,但是当我明确声明它时,这样做最终导致它说 'variable "answer" being used before declaration'。代码有什么问题?

    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'

如您所见,启用大小 类 时会出现 secretAnsarr,但当我禁用它时,它会变得不可见。

只需这样声明您的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)"

在那部分:

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
    }