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

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
  • 1
    Does this answer your question? [How to manually decode an an array in swift 4 Codable?](https://stackoverflow.com/questions/44857326/how-to-manually-decode-an-an-array-in-swift-4-codable) – gcharita Apr 07 '21 at 22:34

1 Answers1

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

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571