【问题标题】:Warning: Value was defined but never used; consider replacing with a boolean test警告:值已定义但从未使用过;考虑用布尔测试替换
【发布时间】:2016-08-21 01:58:30
【问题描述】:

我的函数收到以下警告:

值 intVal 已定义但从未使用过;考虑用布尔测试替换。

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool 
{
    text = (timerTxtFld.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)
    if let intVal = Int(text) {
        timerDoneBtn.alpha = 1
        timerDoneBtn.enabled = true
    } else {
        timerDoneBtn.enabled = false
    }
    return true
}

谁能帮我弄清楚我需要做些什么来摆脱这个错误?

【问题讨论】:

  • 这是一个警告,而不是一个错误......它只是说你创建的值(intVal)没有被使用。您可以用 _ 替换它,它会使警告静音

标签: ios swift function


【解决方案1】:

去掉let,直接对比Int的结果。你无缘无故地创建了intVal,它抱怨说这是一个未使用的变量。

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool 
{
    text = (timerTxtFld.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)
    if Int(text) != nil
    {
        timerDoneBtn.alpha = 1
        timerDoneBtn.enabled = true
    }
    else
    {
        timerDoneBtn.enabled = false
    }
    return true
}

【讨论】:

  • if Int(text) { } 不会编译
  • 哎呀忘记值了。
【解决方案2】:

这不是错误,而是警告。编译器告诉您,您创建了 const intVal 但从未使用过它。

只需将您的 if 语句更改为

if Int(text) != nil
{

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-07
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-06
    相关资源
    最近更新 更多