我一直在努力思考一项看似简单的任务,但始终一事无成。
我的目标是创建一个用户选择流程。 假设我有一份与食物相关的问题 list ,例如:
What is your favourite breakfast? What do you have for dinner? How do you like
your meat cooked? Whats your favourite spaghetti sauce? e.t.c.
以及每个问题的一组回复选项
Q1: <<Pancakes|Waffles>>, Q2: <<Steak|Spaghetti>>, Q3: <<Raw|Welldone>>, Q4: <<Bolognese|Simple cheese>>
如何根据用户在上一个问题中的选择使用一组回复选项加载下一个问题?但主要的问题是我如何让它变得通用和数据驱动——而不需要一堆条件。
我一直在尝试使用Arrays
、NSDictionaries
、NSRegularExpressions
,但无法找到合适的逻辑解决方案。
非常感谢任何见解!
提前谢谢你。
最佳答案
字典的替代方法是自定义类。我认为它提高了可读性,但您可能有自己的看法。
class Question {
var ask: String
var answers: [String]
var nextQuestions = [Question?]()
init(question: String, ans: [String]) {
self.ask = question
self.answers = ans
}
func nextQuestion(answer: String) -> Question? {
var result: Question? = nil
if let index = find(self.answers, answer) {
result = self.nextQuestions[index]
}
return result
}
}
// Set up your test data
let q1 = Question(question: "What is your favourite breakfast", ans: ["Pancakes", "Waffles"])
let q2 = Question(question: "What do you have for dinner", ans: ["Steak", "Spaghetti"])
let q3 = Question(question: "How do you like your meat cooked", ans: ["Raw", "Welldone"])
let q4 = Question(question: "What's your favourite spaghetti sauce", ans: ["Bolognese", "Simple cheese"])
// This is quick and dirty.
// It would be better to have a func to hide the implementation.
q1.nextQuestions.append(q2)
q1.nextQuestions.append(q2)
q2.nextQuestions.append(q3)
q2.nextQuestions.append(q4)
// Pretend "Spaghetti" was the answer for q2
var theQuestion = q2
let userAnswer = "Spaghetti"
if let another = theQuestion.nextQuestion(userAnswer) {
theQuestion = another
}
关于ios - 具有关联数据的重复任务的泛型 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32100967/