0

Im trying to access a variable defined in one class from two other viewControllers. In java I would set the variable as static then I could access it as variables.varOne. Since class variables in Swift are not currently functioning is there a way to accomplish this?

(Example code)

class variables
{
   var varOne = 1
}

class viewController1
{
   func addTwo() //Linked to a button
   {
      variables.varOne += 2
   }
}

class viewController2
{
   func addThree //Linked to a button
   {
      variables.varOne += 3
   }
}

Thanks in advance for the help!

Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
Armand Choy
  • 1
  • 1
  • 1

2 Answers2

4

Yes, class variables are not supported. You can use a "type property" in a structure.

Define your "variables" as a structure, instead of a class.

struct variables {
    static var varOne: Int = 1
}
Louis Zhu
  • 792
  • 5
  • 12
2

As there is no class variable available yet one option you can do is to make singleton and access those variables through singleton.The singletons have thread-safe implementation.Another alternative is you define struct with static variable

class variables {
   //Singleton specific implementation
    class var sharedInstance: variables {
    struct Static {
        static var instance: variables?
        static var token: dispatch_once_t = 0
        }

        dispatch_once(&Static.token) {
            Static.instance = variables()
        }

        return Static.instance!
    }



    var varone = 1

}
class viewController1
{
   func addTwo() //Linked to a button
   {
      variables.sharedInstance.varOne += 2
   }
}

class viewController2
{
   func addThree //Linked to a button
   {
      variables.sharedInstance.varOne += 3
   }
}

So now you can access your variable to any class with same states changed by other classes. Struct Implementation

    struct variables {
           static var varone = 1
     }

With this you can access from another classes

codester
  • 36,891
  • 10
  • 74
  • 72