Class with properties of custom types into UserDefaults

Hi, I am making an iOS video game and want to save the player's data. Is it possible to save an instance of this class into UserDefaults? The class in question has properties that reference other custom classes. This is my class definition:

class Warrior: CombatEligible {
  var name: String = ""
  var gender: String = ""
  var level: Int = 1
  var xp: Int = 0
  var current_dimension: VirtualDimension = Master_Nexus
  var gold: Int = 0
  var weapons: [String] = []
  var completed_dimensions: [VirtualDimension] = []
  var hp: Int = 10
  var items: [Item] = []
  var knocked_out: Bool = false
  var pet: Monster = myPet
  var warrior_created = false
  var defeated_monsters: Int = 0
  var currentTarget: Monster = no_monster
  var maxWeight: Int = 0
  var defeated_bosses: Int = 0
  var inCombat: Bool = checkCombat()
  var targetIsInvisible: Bool = false
  var inBossBattle: MultipleValues = [false, no_boss]
  var invisible: Bool = false
  var hypnotized: Bool = false
  var switchingEnabled: Bool = true
  var switchedToPet: Bool = false
  var stunned: Bool = false
  var errodable_target_weakened: Bool = false
  var errodable_target_weakened_target: Monster = no_monster
  var currentWeapon: Weapon?
}

The class has properties that are instances of other classes for example: var pet: Monster = myPet (myPet is an instance of the Monster class). Therefore, Warrior cannot conform to the Codable protocol and cannot be saved to UserDefaults. What do I do?

How is myPet defined ?

You need to either:

  • define an ID for each instance (e.g. of Monster)

  • store this ID in the UserDefaults of warrior

  • store each instance (e.g. ofMonster), with its ID in UserDefaults

  • When you load from userDefaults, rebuild the objects (e.g., myPet) first, and use it to rebuild warrior, using the id to know which Monster it is.

Did you consider saving a json instead ?

What's an ID? I'm new to UserDefaults.

Here an ID will simply be a unique String or number that let you retrieve the element. Could be the name of Monster (pet) if it is unique (should be).

But show more code if you want more help.

Note: why is pet defined as Monster ?

  • Why not create an alias
  • typealias Pet = Monster
  • That would make code more readable probably.
Class with properties of custom types into UserDefaults
 
 
Q