0
req = ["a":nil, "b":3, "c":["d":3.3, "e":"e", "f":[]], "g":[]]

Traditionally ("if js can do it we can do it too!") if you wanted to just throw any old object in storage you would ...

req: [String: Any?] ... typical api package or whatever
let enc: Data = try! NSKeyedArchiver.archivedData(
                              withRootObject: req, requiringSecureCoding: false)
eg, UserDefaults.standard.set(enc, forKey: "data_rqst")

and then out

let enc: Data = UserDefaults.standard.object(forKey: "data_rqst") as? Data,
let rec = NSKeyedUnarchiver.unarchiveObject(with: enc) as? [String: Any?],

Sadly these days,

'unarchiveObject(with:)' was deprecated in iOS 12.0: Use +unarchivedObjectOfClass:fromData:error: instead

enter image description here

Is there a replacement which allows you to [String: Any?] ?

Unfortunately solutions and mentions I've found are when you have a codable class.

I was surprised to see (unless I have the syntax wrong) you apparently cannot simply use something like [String: Any?]? with .self as the class in unarchivedObjectOfClass#fromData (or "classes") calls.

6
  • How about creating an enum with associated values to represent all the possible things the data can contain? See this answer that does this for JSON. If you really don't want to be type-safe for some reason, do something like this answer, which produces a [String: Any] directly.
    – Sweeper
    Commented Jul 1 at 22:37
  • It's such a shame - they seem to be literally taking away the ability to decode a free, nested, dictionary - sad!
    – Fattie
    Commented Jul 2 at 1:39
  • (I added an example request up top of the question.) You know what I believe the second approach fails anyway with nesting/optional like that @Sweeper . I was surprised to see (unless I have the syntax wrong) you can't simply use something like [String: Any?]? with .self as the class in unarchivedObjectOfClass#fromData (or "classes") calls. Ah well.
    – Fattie
    Commented Jul 2 at 16:20
  • try let enc = UserDefaults.standard.data(forKey: "data_rqst")!; let unarchiver = try! NSKeyedUnarchiver(forReadingFrom: enc); unarchiver.requiresSecureCoding = false; let rec = try! unarchiver.decodeTopLevelObject(of: [NSDictionary.self, NSString.self, NSNumber.self, NSArray.self, NSNull.self], forKey: NSKeyedArchiveRootObjectKey) as! [String: Any?]; print(rec);
    – hanshenrik
    Commented Jul 2 at 16:36
  • my goodness! @hanshenrik I think that sort of works!! - however - I think it might not do nested? its a bit confusing and takes some time to test .. a test is req = ["a":nil, "b":3, "c":["d":3.3, "e":"e", "f":[]], "g":[]]
    – Fattie
    Commented Jul 2 at 17:38

0

Browse other questions tagged or ask your own question.