简体   繁体   中英

How to access an 'outside' variable in a class func in swift?

I have declared a class function in Swift and I wish to be able to access a certain variable in this function which has been declared outside.

var something : Int = 0

and

class func add()
{
}

So I wish to access the value of 'something' in this class func.

Sorry if I sound stupid, still a bit new to Swift so please bear with me.

You should understand what is class func, this is kind of the same as static func with a small difference with overriding rules.

if you want to access var something : Int you need to create an instance of that class.

var classInstance = MyClass() //swift allocates memory and creates an instance
classInstance.something = 5

static variable is a global variable, that can be accessed without creating an instance.

static var something : Int = 4
MyClass.something = 3 //didnt create instance of MyClass

you have to set the value to a static variable when declaring it (or setting a nil as optional)

static var something : int //this will not compile

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM