2

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...

1

1 Answer 1

2

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")]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.