在我的类中,我使用多个变量进行计算,但是当我在 Controller 中启动此类的对象时,我使用字典。
这是简单的代码:
class MyClass {
var one: Float = 1.0
var two: Float = 2.0
var three: Float = 3.0
var four: Float = 4.0
var dictionary = [String: Float]()
init(type: String) { // Here I use dictionary
switch type {
case "type1":
self.dictionary = ["one": one, "two": two]
case "type2":
self.dictionary = ["three": three, "four": four]
default:
break
}
}
func calculate() -> Float { // And here I use variables
return one + two
}
}
在 Controller 中,我需要字典,因为我在 UIPickerView
和 UITableView
标签等中使用键。
但是我需要在字典中的变量和类中的变量之间建立牢固的联系。
所以,当我在 Controller 中使用时:
myClass = MyClass(type: "type1")
override func viewDidLoad() {
super.viewDidLoad()
myClass.dictionary["one"] = 1.5 // ["one": 1.5, "two": 2.0]
print(myClass.one) // 1.0 but I need 1.5
}
当我在字典中进行更改时,我需要更改变量,以便使用更新的变量在类中进行进一步计算。是否可以通过声明 var
和 dictionary
来实现?或者我需要编写一个方法,每次字典更改时都会更新变量?
感谢您的帮助!
最佳答案
最好的方法是将 one
、two
、 Three
、four
转换为计算属性,并由词典。这样,您的属性和字典将始终保持同步:
class MyClass {
var dictionary = [String: Float]()
var one: Float {
get { return self.dictionary["one"]! }
set { self.dictionary["one"] = newValue }
}
var two: Float {
get { return self.dictionary["two"]! }
set { self.dictionary["two"] = newValue }
}
var three: Float {
get { return self.dictionary["three"]! }
set { self.dictionary["three"] = newValue }
}
var four: Float {
get { return self.dictionary["four"]! }
set { self.dictionary["four"] = newValue }
}
init(type: String) {
switch type {
case "type1":
self.dictionary = ["one": 1.0, "two": 2.0]
case "type2":
self.dictionary = ["three": 3.0, "four": 4.0]
default:
break
}
}
func calculate() -> Float {
return one + two
}
}
// Usage:
let myClass = MyClass(type: "type1")
myClass.dictionary["one"] = 1.5
print(myClass.one) // 1.5
print(myClass.calculate()) // 2.0
关于swift - Dictionary 中的变量与类中其他变量之间的联系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37361781/