Morten Balle Petersen Morten Balle Petersen - 2 months ago 22
Swift Question

How to init my array in swift

I have this code for a question and answer app i want to make. It is supposed to ask a random question from the array.
My code is working in playground, but when i put it into an xcode project, it tells me:

Cannot use instance member 'Kat1' within property initializer; property initializers run before 'self' is available

Im new to coding apps and swift, and i dont know how to init the array the right way.

Here is the code im using:

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)`


What am i doing wrong?

Answer

Put your code inside a function....

   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)`
}