-1

I am coding in Swift and I want to set some values for certain keys in the UserDefaults.standardKeys. However, I am trying to do a very simple thing but it doesn't work.

I want the name of the town (selectedTown) to be the value for the key "defaultsKeys.town" and the zip code of the town (selectedPC) to be the value for the key "defaultsKeys.postalCode". However, it seems that the value selectedPC overrides the value of defaultsKeys.town even if I assign it to defaultsKeys.postalCode. How is it possible?

Code:

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)

My keys are defined in a swift file:

struct defaultsKeys {
  static let keyOne = "name"
  static let authentication = "false"
  static let town = ""
  static let postalCode = ""
}
damsc69
  • 7
  • 3
  • How is `defaultsKeys.town` and `defaultsKeys.postalCode` defined? – vadian Jan 09 '18 at 18:14
  • In another Swift file but I don't think it's part of the problem since it works for other actions... – damsc69 Jan 09 '18 at 18:20
  • It shouldn't be able to override unless `defaultKeys.town` and `defaultKeys.postalCode` are the same string. – creeperspeak Jan 09 '18 at 18:23
  • Please update your question showing how your keys are declared and defined. Also show the code where you read these values. – rmaddy Jan 09 '18 at 18:27
  • When I print selectedPC and selectedTown, I get the values I want but the assignment seems not to be working – damsc69 Jan 09 '18 at 18:40
  • 3
    lol, `town` and `postalCode` have the same value (empty string). What do you expect? `UserDefault` keys are required to be unique – vadian Jan 09 '18 at 18:41
  • lol I didn't know that... Thanks for the answer! It worked. I replaced the empty string by some initial values – damsc69 Jan 09 '18 at 18:43

1 Answers1

0

You are setting your town and postalcode to the same key in userDefaults. To fix this change:

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

to:

struct defaultsKeys {
  static let keyOne = "name"
  static let authentication = "false"
  static let town = "town"
  static let postalCode = "postalCode"
}
creeperspeak
  • 5,403
  • 1
  • 17
  • 38