Swift在视图控制器之间传递结构?

时间:2014-08-13 20:57:11

标签: struct swift

我的应用已让用户登录其帐户。然后,应用程序访问Parse.com以检索其所有信息。该信息存储在结构中。我希望在视图控制器之间传递该结构,以便可以在应用程序中随时访问它。我尝试的一切都给了我错误。我无法将其声明为可选项,或者在下一个类中设置相同的结构。解决方案是什么?

2 个答案:

答案 0 :(得分:6)

使用以下代码在ViewControllers之间传递struct

    //FirstViewController.swift

    struct GlobalStruct
    {
    var details:String;
    init()
    {
        details = "global struct";
    }
    };

    class FirstViewController: UIViewController {
    override func viewDidLoad() {
    super.viewDidLoad()
    }
@IBAction func buttonClicked()
    {
        let secondViewController = self.storyboard.instantiateViewControllerWithIdentifier("secondview") as SecondViewController
        var passData = GlobalStruct();
        passData.details = "Secret Information :)";
        secondViewController.setStructDataReference(passData); //passStruct
        self.navigationController.pushViewController(secondViewController, animated: true)
    }
   override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}


//SecondViewController.swift

class SecondViewController:UIViewController
{
    var structData:GlobalStruct;

override func viewDidLoad()
{
    println("struct data = \(self.structData.details)");
}
func setStructDataReference(structDataReference:GlobalStruct)
{
    self.structData = structDataReference;
}

    init(coder aDecoder: NSCoder!)
    {
        self.structData = GlobalStruct();
        super.init(coder: aDecoder);
    }

}

答案 1 :(得分:0)

我将在两个控制器上创建空数组[Struct]。 然后,您在performSegue之前执行的任何操作都应该执行:

self.arrayinmaincontroller.insert(结构,at:0)

并将其传递到func prepare(for segue: UIStoryboardSegue, sender: Any?)