在 swift 中全局更改 var
Change var globaly in swift
我想更改我创建的 swift 文件中 var 的值:
class functions {
var DataSent = "Sensor"
func setValue (DataSent: String) {
self.DataSent = DataSent
}
func getValue () -> String {
return self.DataSent
}
}
当我调用 setValue 时,DataSent 没有改变我该怎么办?
我这样称呼它:
functions().setValue(stringData)
然后我用 getValue
将它调用给另一个 class
您每次调用 functions()
时都会创建一个 functions
的新实例。在这种情况下,最好使用带有 static
函数和静态变量的 struct
。
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)
我想更改我创建的 swift 文件中 var 的值:
class functions {
var DataSent = "Sensor"
func setValue (DataSent: String) {
self.DataSent = DataSent
}
func getValue () -> String {
return self.DataSent
}
}
当我调用 setValue 时,DataSent 没有改变我该怎么办?
我这样称呼它:
functions().setValue(stringData)
然后我用 getValue
将它调用给另一个 class您每次调用 functions()
时都会创建一个 functions
的新实例。在这种情况下,最好使用带有 static
函数和静态变量的 struct
。
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)