【问题标题】:Variable 'myCellChoice' was never mutated inside if statement in didSelectRowAt indexPath function变量“myCellChoice”从未在 didSelectRowAt indexPath 函数的 if 语句中发生变异
【发布时间】:2018-04-01 21:36:57
【问题描述】:

我有函数 didSelectRowAt indexPath,里面有一个 if 语句。

myButtonChoiceString2 成功传递了从前一个视图控制器中选择的按钮的 String title.text。

删除 if else 语句后,代码可以工作,但只能显示背部锻炼,因此包含此 if else 以显示肩部锻炼。

请你看看我在 if else 中做错了什么以获得这些警告:

  • 第一个警告:变量“myCellChoice”从未发生突变;考虑更改为“让”常量
  • 第二个警告:从未使用不可变值“myCellChoice”的初始化
  • 第三个警告:从未使用过不可变值“myCellChoice”的初始化

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //First Warning Below
        var myCellChoice = DataService.instance.backWorkouts[indexPath.row]
    
        if myButtonChoiceString2 == "BACK" {
            //Second Warning Below
            let myCellChoice = DataService.instance.backWorkouts[indexPath.row]
        } else if myButtonChoiceString2 == "SHOULDERS" {
            //Third Warning Below
            let myCellChoice = DataService.instance.shoulderWorkouts[indexPath.row]
        }
    
        videoPlayer.loadVideoID(myCellChoice.videoCode)
    }
    

【问题讨论】:

    标签: ios swift if-statement


    【解决方案1】:

    实际上是第一个 var 的警告,因为它应该被声明为 let 而不是 var 因为在该方法上您从未为其赋值,因此它是常量而不是变量,关于其他两个警告都在 if----else 声明中声明,其中两个都没有被使用,实际上是行

     videoPlayer.loadVideoID(myCellChoice.videoCode)
    

    读取myCellChoice var 声明最多顶,这个

     var myCellChoice = DataService.instance.backWorkouts[indexPath.row]
    

    不是在 if-----else 语句中声明的那些,所以从编译器的逻辑来看,它们都是无用

    所有都应该这样重写

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    
          if myButtonChoiceString2 == "BACK" {
    
                let myCellChoice = DataService.instance.backWorkouts[indexPath.row]
    
                videoPlayer.loadVideoID(myCellChoice.videoCode)
    
            } else if myButtonChoiceString2 == "SHOULDERS" {
    
                let myCellChoice = DataService.instance.shoulderWorkouts[indexPath.row]
    
                videoPlayer.loadVideoID(myCellChoice.videoCode)
    
          }
    }
    

    【讨论】:

    • 太棒了,谢谢!这行得通,我认为我面临的主要问题是将 videoPlayer.loadVideoID(myCellChoice.videoCode) 留在 if 语句之外。干杯
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    • 1970-01-01
    • 2018-03-13
    • 2020-08-31
    相关资源
    最近更新 更多