【问题标题】:No exact matches in call to initializer - Swift 2D array调用初始化程序没有完全匹配 - Swift 2D 数组
【发布时间】:2021-04-23 21:22:14
【问题描述】:

出现问题时,我正在创建简单的测验应用程序。

我有一个到 UILabel 的 IBOutlet 连接:

@IBOutlet weak var questionText: UILabel!

还有问题和正确答案:

let questions = [["1 + 1 = 2", true],
                     ["2 + 2 * 2 = 8", false],
                     ["It's third question", true]]

"Cannot assign value of type 'Any' to type 'String'" 错误,当更改问题时:

func nextQuestion(num: Int){
        questionNum += 1
        questionText.text = questions[num][0] // <- error is here
    }

当我尝试强制字符串时,"no exact matches in call to initializer" 出现了,即使我说这是一个字符串并且没有理由计算它: questionText.text = String(questions[num][0])

唯一有效的代码是:

questionText.text = questions[num][0] as? String

我打扰为什么?我不明白为什么 String() 是错误的并且 as! 会产生警告 “将强制向下转换为 'String' 作为可选将永远不会产生 'nil' "

questionText.text = questions[num][0] as! String

【问题讨论】:

    标签: swift


    【解决方案1】:

    根据您的声明,questions 的类型是[[Any]],这导致了您所描述的错误。

    最好以类型安全的方式做事。

        let questions = [
            ("1 + 1 = 2", true),
            ("2 + 2 * 2 = 8", false),
            ("It's third question", true)
        ]
    
        func nextQuestion(num: Int){
            questionNum += 1
            questionText.text = questions[num].0
        }
    

    或者为questions的元素定义一个结构会是更可取的方式。

    【讨论】:

      【解决方案2】:

      根据有关使用结构的建议,我设法在我的项目中创建了一个新文件,我在其中定义了问题结构。

      struct Question{
          let title: String
          let answer: Bool
          
          init(title: String, answer: Bool){
              self.title = title
              self.answer = answer
          }
      }
      

      然后我就可以像上面那样创建问题了。

      let questions = [
              Question(title: "1 + 1 = 2", answer: true),
              Question(title: "2 + 2 * 2 = 8", answer: false),
              Question(title: "It's third question", answer: true)
          ]
      
      questions[questionNum].title
      questions[questionNum].answer
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-14
        • 2022-11-19
        • 2022-08-02
        • 1970-01-01
        • 2020-08-22
        • 2022-01-15
        • 2021-09-19
        • 2020-10-29
        相关资源
        最近更新 更多