Shared (or static) variable in Swift

I have a class with an array whose values ​​come from a text file. I would like to read these values ​​once and store them in a shared variable, allowing other classes to access those values.

How can I do this in Swift?

UPDATE:

Suppose I have three classes of animals, and which ones can be found in a variety of locations that are loaded from different tables (each animal has yours, and the structure for each is different). I would like to be able to use them to bind to a specific class:

  • clBirds.Places
  • clDogs.Places
  • clCats.Places

Please note that I need to load the data once. If I don't have a shared variable and need to put it outside the class, I will need to have different names for the methods, for example:

  • BirdsPlaces
  • DogsPlaces
  • CatsPlaces

And we have no legacy in this case

0


source to share


1 answer


Declare the variable at the top level of the file (outside of any classes).

NOTE : Variables at the top level of the file are lazy initialized! This way, you can set a default value for your variable as the result of reading the file, and the file won't actually be read until your code first requests the value of the variable. Cool!

Similarly, you can declare an enum or struct at the top level of the file (outside of any classes), and now it is global. Here's an example from my own code:



struct Sizes {
    static let Easy = "Easy"
    static let Normal = "Normal"
    static let Hard = "Hard"
    static func sizes () -> String[] {
        return [Easy, Normal, Hard]
    }
    static func boardSize (s:String) -> (Int,Int) {
        let d = [
            Easy:(12,7),
            Normal:(14,8),
            Hard:(16,9)
        ]
        return d[s]!
    }
}

      

Now any class can reference Sizes.Easy

or Sizes.boardSize(Sizes.Easy)

etc. Using this method, I removed all magic numbers and magic strings (for example, NSUserDefault keys) from my code. It's much simpler than Objective-C, and much cleaner because (as the example shows) a struct (or enum) gives you a kind of miniature namespace.

+3


source







All Articles