ansanes
ansanes

Reputation: 117

Check Data type for a serialized object in Swift

I have 2 classes (Client, Admin) that inherit from the same parent class (User).

Those 3 classes implement the NSCoding protocol so I can store them in the userdefaults as Data.

When my application starts I want to deserialized the stored Data into Swift objects.

Is there a way to know which type the stored Data belongs to?

something like this:

let data = defaults.object(forKey: "loggedInUser") as? Data
if data is Client
     let client = NSKeyedUnarchiver.unarchiveObject(with: data) as? Client
if data is Admin
     let admin = NSKeyedUnarchiver.unarchiveObject(with: data) as? Admin

Upvotes: 1

Views: 264

Answers (1)

Danh Huynh
Danh Huynh

Reputation: 2327

You can check

if let data = defaults.object(forKey: "loggedInUser") as? Data {
    let obj = NSKeyedUnarchiver.unarchiveObject(with: data)

    if obj is Client {
        let client = obj as! Client
    }

    if obj is Admin {
        let admin = obj as! Admin
    }
}

Upvotes: 1

Related Questions