How to create struct data globally accessible in a

2020-02-29 09:13发布

问题:

I'm very new to iOS programming and swift. I am trying to create a singleton class to store my global data. My global data are a struct and an array of this struct. I want to have only one instance of this class, thus a singleton class. Global data should be accessible and editable to all ViewControllers. I have been searching around and I almost have it figured out except one last part. Here is the singleton class:

    import Foundations
    class Global {

     struct Info {
      var firstname:String!
      var lastname:String!
      var status:String!

      init (firstname:String, lastname:String, status:String)
       {
        self.firstname=firstname
        self.lastname=lastname
        self.status=status
       }
    }

   var testString: String="Test" //for debugging
   var member:[Info]=[]

    class var SharedGlobal:Global
     {
      struct Static 
      {static let instance = Global()}
      return Static.instance
     }
    }

Now I want to access the global variables of this singleton class from some viewControllers. When I type this in xcode:

    Global.SharedGlobal.

I get two options one is the array member and the other is the testString. The struct Info is not available. However, if I just type

    Global.

then I see Global.Info and Global.SharedGlobal as my options.

Why is that I can't access the struct in my singleton class (i.e. Global.SharedGlobal.Info)? I am missing something? I appreciate any feedback or help. Thanks a lot in advance.

回答1:

Unless there's a very specific reason to do it, you don't need to nest classes like that.

Let's simplify a bit your code for the exercise:

struct Info {
    // No need for these properties to be Implicitly Unwrapped Optionals since you initialize all of them
    var firstname: String
    var lastname: String
    var status: String

    init (firstname:String, lastname:String, status:String) {
        self.firstname=firstname
        self.lastname=lastname
        self.status=status
    }
}

class Global {

    // Now Global.sharedGlobal is your singleton, no need to use nested or other classes
    static let sharedGlobal = Global()

    var testString: String="Test" //for debugging

    var member:[Info] = []

}


// Use the singleton like this
let singleton = Global.sharedGlobal

// Let's create an instance of the info struct
let infoJane = Info(firstname: "Jane", lastname: "Doe", status: "some status")

// Add the struct instance to your array in the singleton
singleton.member.append(infoJane)

Now it would make sense to me. A struct holding info about some user, and I can make any number instances of them - and a singleton class, unique, were I can store these Info instances, this singleton being usable anywhere.

Is it the kind of thing you wanted to achieve?