Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 672
genaks Avatar asked Mar 16 '23 00:03

genaks


1 Answers

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
like image 89
Daniel Krom Avatar answered Apr 02 '23 10:04

Daniel Krom