所以这是我的代码,用于迭代 JSON 字典,并在我的控制台上打印每个问题,而不是问题标题。
for x in r {
if(x.0.containsString("Question")){
print(x.1)
self.questionLabel.text = (x.1) as! String
} else if (x.0.containsString("Ladder")) {
print(x.1)
}
}
我希望能够通过按 NEXT 按钮来控制循环,然后再循环到下一个问题。我该怎么做?
最佳答案
字典是一种序列类型,位于生成器之上。生成器通过名为 next() 的方法来促进循环。通过调用 next(),您可以访问序列中的下一项。以下内容应该可以帮助您最大程度地实现您所追求的目标:
let dict = ["Question":"What is the population of ...",
"Ladder" : "Something else I guess?"]
var generator = dict.generate()
func nextQuestion() -> String? {
if let pair = generator.next() {
if pair.0.containsString("Question") {
return pair.1
}
// recusively calls itself until if finds another question
// or runs out of entries
return nextQuestion()
}
// no more entries in the dictionary
return nil
}
print(nextQuestion()) // prints: Optional("What is the population of ...")
print(nextQuestion()) // prints: nil
所以基本上,nextQuestion() 将搜索生成器,直到找到下一个问题并返回它。它要么会耗尽要搜索的内容,因此返回 nil,要么会找到下一个问题并返回该问题。
关于json - 使用调查问题运行 JSON 字典循环 SWIFT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37488867/