swift - Dictionary 中的变量与类中其他变量之间的联系

标签 swift variables dictionary

在我的类中,我使用多个变量进行计算,但是当我在 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 中,我需要字典,因为我在 UIPickerViewUITableView 标签等中使用键。

但是我需要在字典中的变量和类中的变量之间建立牢固的联系。

所以,当我在 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
}

当我在字典中进行更改时,我需要更改变量,以便使用更新的变量在类中进行进一步计算。是否可以通过声明 vardictionary 来实现?或者我需要编写一个方法,每次字典更改时都会更新变量?

感谢您的帮助!

最佳答案

最好的方法是将 onetwo Threefour 转换为计算属性,并由词典。这样,您的属性和字典将始终保持同步:

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/

相关文章:

ios - swift:可以同时下载的文件数

ios - 检查应用程序是否是在 iPad 上打开的 iPhone 应用程序

css - 如何基于 CSS 选择器用另一个值覆盖 SASS 变量?

xml - 使用 Ansible 在 Jinja2 中转义特殊 XML 字符

python:查找围绕某个 GPS 位置的圆的 GPS 坐标的优雅方法

Python dict 使用点符号和链接

swift - 一组具有可选字符串属性的对象,改进接受字符串参数的函数并在集合中找到最佳匹配

ios - 摇动手势不适用于 iOS

php - file_get_content 和变量问题

asp.net - 如何在VB.net中使用字典?