Shared (or static) variable in Swift

I have a class with an array which values comes from a text file. I would like to read this values once and store them in a shared variable, making possible other classes access that values.

How can I do that in Swift?

  • Swift, variable with same as a method name
  • Resize textField Based On Content
  • NSUserDefaults Custom object - Property list invalid for format: 200 (property lists cannot contain objects of type 'CFType')
  • How to get height of Keyboard? (swift)
  • Assure Delivery Of UILocalNotification on correct time ios
  • How to get notified in contact changed event in IOS?
  • UPDATE:

    Suppose I have three classes of animals and which of them can be found in a set of places which is load from differents tables (each animal have yours and the structure is different for each one). I would like to be able to use them linking to specific class:

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

    Note that I need to load data once. If I dont´t have a shared variable and need to put it outside the class, I need to have different names to the methods, just like:

    • BirdsPlaces
    • DogsPlaces
    • CatsPlaces

    And we don´t have heritage in this case

    Solutions Collect From Internet About “Shared (or static) variable in Swift”

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

    NOTE: variables at the top level of a file are initialized lazily! So you can set the default value for your variable to be the result of reading the file, and the file won’t actually be read until your code first asks for the variable’s value. Cool!

    Similarly, you can declare an enum or struct at the top level of a file (outside 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 refer to Sizes.Easy or Sizes.boardSize(Sizes.Easy), and so on. Using this technique, I’ve removed all the “magic numbers” and “magic strings” (such as NSUserDefault keys) from my code. This is much easier than it was in Objective-C, and it is much cleaner because (as the example shows) the struct (or enum) gives you a kind of miniature namespace.