Accessing getter and setter from other viewcontroller

317 Views Asked by At

In my class A, i have a variable defined as follows:

var auth_token:String?
var _auth_token:String {get{return self.auth_token!} set{auth_token = newValue}

now i want to access this auth_token from other viewcontroller class. How can i achieve this. If i make a new instance of the class it will return me nil as expected.

1

There are 1 best solutions below

1
On

You can make your class A singleton using,

import Foundation

class A {
    static var sharedInstance = A()
    var myVariable : String! = nil

    private init () {
        //no need for any implementation
        //empty init removes all possibility of duplicate instance of class A
    }

}

As you can see there is a static variable named sharedInstance and a string variable called myVariable in class A.

Declaring sharedInstance as static and providing empty implementation of private init makes your Class A singleton.

Now whatever you set the value of myVariable no matter where all your VCs will get the same value :)

You can access it using,

let test = A.sharedInstance.myVariable

Hope it helps :) Have fun