How to create struct data globally accessible in a singleton class in swift 2.0 (iOS)?

前端 未结 1 537
野的像风
野的像风 2021-01-01 06: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

相关标签:
1条回答
  • 2021-01-01 06:55

    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?

    0 讨论(0)
提交回复
热议问题