Segue没有转移阵列

时间:2015-06-08 11:32:52

标签: arrays swift segue

我似乎无法理解为什么每次运行测试程序时数组的答案都是空的。

当我在视图控制器1中使用println(finalResultsSegue)时,我可以看到结果数组,但是当我将它传递给视图控制器2中的答案时,它会转到下一个屏幕,但数组仍为空。

查看控制器1

@IBAction func submitAll(sender: UIButton) {

    let hasAnsweredAllQuestions = questions.reduce(true) { (x, q) in x && (q.usersAnswer != nil) }

    println("has user answered all questions?: \(hasAnsweredAllQuestions)")

    if hasAnsweredAllQuestions == true {

        for (index, _) in enumerate(questions) {
            userAnswers.append(questions[index].usersAnswer!)
            correctAnswers.append(questions[index].answer!)
        }
        if userAnswers.count == 3 {
                checkResults()
                }
            }
        }
    }

func checkResults() {
    let answer = map(zip(correctAnswers, userAnswers)){
        ($0.0 == $0.1) ? "correct" : "wrong"
    }
    var finalResults = answer.map({"The following answer is \($0)"})

    finalResultsSegue = finalResults

    println(finalResultsSegue)
}

@IBAction func nextPage(sender: AnyObject) {

    self.performSegueWithIdentifier("answerSummary", sender: sender)

    func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {

        if(segue.identifier == "answerSummary") {
            var answerSummary = segue.destinationViewController as! QuizResultsViewController

            answerSummary.answers = finalResultsSegue
        }
    }
}

查看控制器2

class QuizResultsViewController: UIViewController {

@IBOutlet weak var testLabel: UILabel!

var answers: [String] = []

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.

    println(answers)

}

2 个答案:

答案 0 :(得分:0)

您在prepareForSegue内已将nextPage作为嵌套函数。将它移到外面它应该可以正常工作:

@IBAction func nextPage(sender: AnyObject) {
    self.performSegueWithIdentifier("answerSummary", sender: sender)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    if let answerSummary = segue.destinationViewController as? QuizResultsViewController
        where segue.identifier == "answerSummary"

        answerSummary.answers = finalResultsSegue
    }
}

您没有必须在func prepareForSegue...前加override这一事实,这暗示您已将prepareForSegue置于错误的位置。

答案 1 :(得分:0)

另一种选择是使用结构来存储您想要从一个ViewController发送到另一个ViewController的任何“全局变量”。在struct中设置一个变量,只要在类之外定义struct,就可以在项目中的任何其他类中访问它。