Search code examples
iosswiftjsondecoder

Where does JSONDecoder().decode get it's data from?


My apologies if this sounds dumb but where does JSONDecoder get its data from? I keep getting "Grid" and "Red" so I think its just decoding this dummy I set up and not the JSONEncoder().encode(myStarageObject) from the last time the program ran. Here is my code that I've managed from seeing online tutorials and examples:

private func loadMyObject() -> MyObject? {
  let jsonString = """
  {
   "type":"Grid",
    "color":"Red",
    "lineThickness":2
  }
  """
  if let jsonData = jsonString.data(using: .utf8) {
    do {
      let loadedObject = try JSONDecoder().decode(myStorageStruct.self,from: jsonData)
      print("I loaded type \(loadedObject.type) of color: \(loadedObject.color)")
      return makeMyObjectFromStorageData(loadedObject)
      } else {
        return nil
      }
    } catch  let error { print(error) }
  } else {
    return nil
  }
return nil
}

Solution

  • For small amounts of data storage I found writing with

    let userDefaults = UserDefaults.standard
    userDefaults.set(yourTypeVariable,"type")
    

    and reading with

    let userDefaults = UserDefaults.standard
    let defaultType = userDefaults.string("type")
    

    worked just fine.