已声明的变量显示'声明前使用的变量'

时间:2015-07-23 06:35:07

标签: swift variables 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'

的屏幕截图

sizeclassesenable

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

2 个答案:

答案 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
    }
相关问题