Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何创建可在Swift中全局访问的结构?_Swift_Model View Controller - Fatal编程技术网

如何创建可在Swift中全局访问的结构?

如何创建可在Swift中全局访问的结构?,swift,model-view-controller,Swift,Model View Controller,我的想法是创建一个类购物车,其中包含一个类订单,该类订单还包括一个struct orderHeader和一个struct orderItems数组 从不同的VC我需要能够更新购物车中的任何项目或订单标题中的信息。我应该在哪里实例化cart类及其变量以使其在所有VC中都可用?您可以创建一个结构来存储所有全局变量和其他数据 Class CommonData{ public static var liveCart:Cart? //anything do you want to stor

我的想法是创建一个类购物车,其中包含一个类订单,该类订单还包括一个struct orderHeader和一个struct orderItems数组


从不同的VC我需要能够更新购物车中的任何项目或订单标题中的信息。我应该在哪里实例化cart类及其变量以使其在所有VC中都可用?

您可以创建一个结构来存储所有全局变量和其他数据

Class CommonData{
        public static var liveCart:Cart? //anything do you want to store globally in app
        public static var loginUser:User?
}
然后,您可以在应用程序中的任何位置修改或获取数据

CommonData.cart?.setTotal(total:100.00) //add data to the cart using mutable functions
CommonData.cart?.total //get data from cart
这是购物车的示例结构

struct Cart{
     let id:Int
     .
     .
     .
     var subTotal:Double
     var total:Double

        //this is the mutable function. this is similar to encapsulation setter in OOP
        mutating func setTotal(total:Double){
             self.total = total
        }
    }