2016-10-05 27 views
0

我有這個問題和答案應用程序的代碼,我想。它應該問陣列中的一個隨機問題。 我的代碼在操場上工作,但是當我將它放入一個xcode項目時,它告訴我:如何在swift中初始化我的數組

無法在屬性初始值設定項中使用實例成員'Kat1'屬性初始值設定項在'self'可用之前運行

Im新編程應用程序和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

我相信你需要把它放在一個函數或viewDidLoad中()內 – Starlord

+0

記住arc4Random不是真正隨機的,你可能會一遍又一遍地結束了相同的號碼。 – Starlord

+0

@Joakim不,「rand」是僞隨機的,但「arc4random_uniform」是隨機的。 – Moritz

回答

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

不錯...這件作品..你能告訴我爲什麼它需要在那裏嗎? –

+0

mmm ok,看看這裏:https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html – Rob

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) 
+0

這仍然給出了同樣的錯誤。這是否需要在viewDidLoad()內? 無法在屬性初始值設定項中使用實例成員'測驗';屬性初始值設定項在'self'可用之前運行 如何將qa.question和qa.answer放置在標籤或故事板的底部。如果我把它放在viewDidLoad()中,我只是得到相同的錯誤,當我ry在viewDidLoad()以外的地方使用它 –

+0

該結構可以獨立存在於單獨的文件中。最後四行放在viewDidLoad()中。最後的兩個打印語句應該被替換以適應其他代碼。 –