Swift中UserDefaults.set的奇怪错误

时间:2018-01-09 18:10:49

标签: swift

我在Swift编码,我想为UserDefaults.standardKeys中的某些键设置一些值。但是,我试图做一个非常简单的事情,但它不起作用。

我希望城镇的名称(selectedTown)是键“defaultsKeys.town”的值,城镇的邮政编码(selectedPC)是键“defaultsKeys.postalCode”的值。但是,似乎selectedPC的值会覆盖defaultsKeys.town的值,即使我将其分配给defaultsKeys.postalCode也是如此。怎么可能?

代码:

let userDefaults = UserDefaults.standard
let selectedPC = Array(tableData.keys)[indexPath.row]
let selectedTown = tableData[selectedPC]!
userDefaults.set(selectedTown, forKey: defaultsKeys.town)
userDefaults.set(selectedPC, forKey: defaultsKeys.postalCode)
performSegue(withIdentifier: "goBackMenu", sender: nil)

我的密钥在swift文件中定义:

struct defaultsKeys {
  static let keyOne = "name"
  static let authentication = "false"
  static let town = ""
  static let postalCode = ""
}

1 个答案:

答案 0 :(得分:0)

您正在将您的城镇和邮政编码设置为userDefaults中的相同密钥。要解决此更改:

struct defaultsKeys {
  static let keyOne = "name"
  static let authentication = "false"
  static let town = ""
  static let postalCode = ""
}

为:

struct defaultsKeys {
  static let keyOne = "name"
  static let authentication = "false"
  static let town = "town"
  static let postalCode = "postalCode"
}