ViewController.Type 没有成员名称 'answerOne' - SWIFT

ViewController.Type does not have a member names 'answerOne' - SWIFT

我正在制作一个 swift 应用程序。这是一个有趣的琐事应用程序,我遇到了一个我以前从未见过的问题。 (我是 swift 和 ios 开发错误的新手)

import UIKit

class TriviaViewController: UIViewController {

@IBOutlet var myQuestionCounter: UILabel!
@IBOutlet var myQuestion: UILabel!
@IBOutlet var firstAnswer: UIButton!
@IBOutlet var secondAnswer: UIButton!
@IBOutlet var thirdAnswer: UIButton!
@IBOutlet var fourthAnswer: UIButton!



var timer = NSTimer() //TO-DO
var count = 0
var questionCounter = 0

var firstQuestion = "What was the first planet to be discovered using the telescope, in 1781?"
var answerOne = "Mercury"
var answerTwo = "Uranus"
var answerThree = "Venus"
var answerFour = "Jupiter"

var firstCorrectAnswer = 2

//This next line gives the ERROR
let questionOneArray = [answerOne, answerTwo, answerThree, answerFour, firstCorrectAnswer]

}

当我声明 "questionOneArray" 时,它显示 "TriviaViewController does not have a member named 'answerOne'"

请向我解释这个错误是什么以及如何修复它。 谢谢。

解决方案 1:您的代码不在方法中,您必须将其包装在方法中。检查这个 Whosebug answer

解决方案 2:将 questions and answers 保留在 struct 中并访问它们,如果您不想将其包装在函数中的话。

struct firstQuestion {
    static var question = "What was the first planet to be discovered using the telescope, in 1781?"
    static var answerOne = "Mercury"
    static var answerTwo = "Uranus"
    static var answerThree = "Venus"
    static var answerFour = "Jupiter"
    static var correctAnswer = "Correct Answer"
}

var questionOneArray = [firstQuestion.answerOne, firstQuestion.answerTwo, firstQuestion.answerThree, firstQuestion.answerFour, firstQuestion.correctAnswer]