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 performSegueWithIdentifier shows black screen
  • Shoot bullet in the Direction the Ship is Facing Swift and Sprite Kit
  • How do you use Interface builder with Swift?
  • Creating environment variables in Xcode 6.0 schema and obtaining them back from code in swift
  • FacebookShare causing compiler error after update
  • Use Safe Area Layout programmatically

    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 = [
            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.