mike vorisis mike vorisis - 6 months ago 11
Swift Question

Change var globaly in swift

I want to change the value of a var in a swift file that i create:

class functions {

var DataSent = "Sensor"

func setValue (DataSent: String) {
self.DataSent = DataSent
}

func getValue () -> String {
return self.DataSent
}


}


when i call setValue the DataSent doesn't change what can i do?

i call it like that:

functions().setValue(stringData)


and then i call it to another class with getValue

kye kye
Answer

You're creating a new instance of functions each time you call functions(). It's best to use a struct with static functions and static variables in situations like this.

struct functions {

    static var DataSent = "Sensor"

    static func setValue (DataSent: String) {
      self.DataSent =  DataSent
    }

    static func getValue () -> String {
        return self.DataSent
    }
}

print(functions.DataSent)
functions.setValue(DataSent: "Blaah")
print(functions.DataSent)