user15575558
user15575558

Reputation:

Decode an Array of an custom struct in Swift out of the UserDefaults

I want to encode an Array of my own struct, which I want to save in UserDefaults, and then read It out (after decoding it). I know how to code the first part (following), that means how to encode an array and save it in Userdefaults.

struct mystruct: Codable {
var int: Int
var string: String
}

var array = [mystruct(int: 2, string: "Example"), mystruct(int: 5, string: "Other Example")]

var encodedArray = try JSONEncoder().encode(array)

UserDefaults.standard.set(encodedArray, forKey: "array")

I also know how to get the data back from the Userdefaults:

var newArray = UserDefaults.standard.data(forKey: "array")

But I don't know how to decode an whole array...

Upvotes: 2

Views: 686

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236458

You just need to pass your custom structure array type [MyStruct].self to the JSONDecoder:


struct MyStruct: Codable {
    let int: Int
    let string: String
}

let myStructures: [MyStruct] = [.init(int: 2, string: "Example"),
                         .init(int: 5, string: "Other Example")]

do {
    let encodedData = try JSONEncoder().encode(myStructures)
    UserDefaults.standard.set(encodedData, forKey: "array")
    if let decodedData = UserDefaults.standard.data(forKey: "array") {
        let decodedArray = try JSONDecoder().decode([MyStruct].self, from: decodedData)
        print(decodedArray)
    }
} catch {
    print(error)
}

This will print:

[MyStruct(int: 2, string: "Example"), MyStruct(int: 5, string: "Other Example")]

Upvotes: 2

Related Questions