我有这个代码用于我想要的问答应用程序。它应该从数组中提出一个随机问题。 我的代码在操场上工作,但当我把它放入xcode项目时,它告诉我:
无法使用实例成员' Kat1'在属性初始化器内;属性初始化程序在“自我”之前运行是可用的
我是编码应用程序和swift的新手,我不知道如何以正确的方式初始化数组。
以下是使用的代码:
var Kat1: [(question: String, answer: String)] =
[
("What is the capital of Alabama?", "Montgomery"),
("What is the capital of Alaska?", "Juneau"),
("What is the capital of Test?", "Test Town")
]
var antal = (Kat1.count)
var randomtal = Int(arc4random_uniform(UInt32(antal)))
print(Kat1[randomtal].question)
print(Kat1[randomtal].answer)`
我做错了什么?
答案 0 :(得分:2)
将代码放在函数中....
override func viewDidLoad() {
super.viewDidLoad()
var Kat1: [(question: String, answer: String)] =
[
("What is the capital of Alabama?", "Montgomery"),
("What is the capital of Alaska?", "Juneau"),
("What is the capital of Test?", "Test Town")
]
var antal = (Kat1.count)
var randomtal = Int(arc4random_uniform(UInt32(antal)))
print(Kat1[randomtal].question)
print(Kat1[randomtal].answer)`
}
答案 1 :(得分:0)
您可能希望将问题和答案打包成一个可以容纳所有问题的结构,并根据要求提供个别问题。这将允许您将存储问题的代码和呈现问题的代码分开。
struct Quiz {
var kat1: [(question: String, answer: String)] =
[("What is the capital of Alabama?", "Montgomery"),
("What is the capital of Alaska?", "Juneau"),
("What is the capital of Test?", "Test Town")]
func randomQuestion() -> (question: String, answer: String) {
let randomtal = Int(arc4random_uniform(UInt32(kat1.count)))
return kat1[randomtal]
}
}
let quiz = Quiz()
let qa = quiz.randomQuestion()
print(qa.question)
print(qa.answer)