Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 从其他viewcontroller访问getter和setter_Swift_Getter Setter - Fatal编程技术网

Swift 从其他viewcontroller访问getter和setter

Swift 从其他viewcontroller访问getter和setter,swift,getter-setter,Swift,Getter Setter,在我的类A中,我有一个变量定义如下: var auth_token:String? var _auth_token:String {get{return self.auth_token!} set{auth_token = newValue} 现在,我想从其他viewcontroller类访问此身份验证令牌。我怎样才能做到这一点。如果我创建一个新的类实例,它会像预期的那样返回nil 您可以使用 进口基金会 class A { static var sharedInstance = A(

在我的类A中,我有一个变量定义如下:

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

现在,我想从其他viewcontroller类访问此身份验证令牌。我怎样才能做到这一点。如果我创建一个新的类实例,它会像预期的那样返回nil

您可以使用

进口基金会

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
    }

}
如您所见,在类a中有一个名为sharedInstance的静态变量和一个名为myVariable的字符串变量

将sharedInstance声明为静态并提供私有init的空实现会使类成为单例

现在,无论您设置myVariable的值是什么,无论您的所有VC在哪里都将获得相同的值:)

您可以使用

let test = A.sharedInstance.myVariable

希望有帮助:)玩得开心

让你的班级成为单身学生!然后访问_auth_token property声明两个类似变量的目的是什么?为什么在强制展开时,
auth_token
是可选的?谢谢。我用你的方法解决了这个问题。