我理解prepareForSegue函数,但我不确定如何设置一个可以接收实例的空变量。
swift 4 / Xcode 9.2
// I want to be able to send classes that look like this to var pickedQuiz
class mathQuestionBank {
var list = [Questions]()
init() {
let item = Questions(text: "What is two plus two?", correctAnswer: "four", textA: "three", textB: "four", textC: "five", textD: "9y" )
list.append(item)
list.append(Questions(text: "How many sides does a triangle have?", correctAnswer: "three", textA: "two", textB: "four", textC: "three", textD: "five"))
list.append(Questions(text: etc....
}
}
class QuestionsViewController: UIViewController {
var pickedQuiz = mathQuestionBank()
// I want to send the entire instance of mathQuestionBank() to var
pickedQuiz. How do I setup the variable pickedQuiz to receive instances
like mathQuestionBank() ? I'd think it needs to be empty so that it can
receive the instance from the prepareForSegue() function.
}
答案 0 :(得分:0)
您只需使用prepareForSegue()
,
let valueToPass = "HelloWorld"
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "segueIdentifier" {
if let nextVC = segue.destinationViewController as? NextViewController {
nextVC.yourVariable = valueToPass
}
}
}
在您的其他课程中,您可以按如下方式定义变量:
class NextViewController {
var yourVariable = ABCType()
}
答案 1 :(得分:0)
“传递一个实例”并不清楚你的意思。你的意思是传递一些自定义对象的实例,而不仅仅是像字符串这样的值类型?只需将@ Madhur示例中的yourVariable更改为所需的类类型:
class ClassToPass {
value1: String?
value2: Data?
value3: Int
init(value1: String?, value2: Data?, value3: Int?) {
self.value1 = value1
self.value2 = value2
self.value3 = value3
}
}
class myViewController: UIViewController {
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "segueIdentifier" {
if let nextVC = segue.destinationViewController
as? NextViewController {
let valueToPass = ClassToPass(value1: "A String",
value2: nil,
value3: 7)
nextVC.yourVariable = valueToPass
}
}
}
}
//And in the other view controller:
class NextViewController {
var yourVariable: ClassToPass? = nil
}