ios - 具有关联数据的重复任务的泛型 - Swift

标签 ios arrays swift generics nsdictionary

我一直在努力思考一项看似简单的任务,但始终一事无成。

我的目标是创建一个用户选择流程。 假设我有一份与食物相关的问题 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>>

如何根据用户在上一个问题中的选择使用一组回复选项加载下一个问题?但主要的问题是我如何让它变得通用和数据驱动——而不需要一堆条件。

我一直在尝试使用ArraysNSDictionariesNSRegularExpressions,但无法找到合适的逻辑解决方案。

非常感谢任何见解!

提前谢谢你。

最佳答案

字典的替代方法是自定义类。我认为它提高了可读性,但您可能有自己的看法。

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/

相关文章:

没有应用内购买机制的 iOS 试用应用

arrays - 在 MATLAB 中将混合数据元胞数组保存到 ascii 文件

ios - 如何从不在 Storyboard 中但以编程方式创建的 View Controller 呈现 "main" Storyboard 中的 View Controller ?

ios - 如果位置关闭,swift 2 会阻止程序运行

ios - 我希望两个按钮具有相同的宽度并使用自动布局从屏幕顶部按比例在所有屏幕尺寸中定位自己?

ios - 当主应用程序未打开时,Swift 如何从今天的扩展中打开特定的 View Controller

ios - UITableViewCell 持有 UICollectionView 并点击集合单元格 segue

JavaScript 扩展数组并向子原型(prototype)添加方法?

php - 如何保持收集的数据库行的顺序与传递给 where 子句的数组相同

swift - 在初始化程序中设置关联属性