how to decode array of custom objects decodable

Asked on 08/22/2024

1 search

To decode an array of custom objects that conform to the Decodable protocol in Swift, you can use the JSONDecoder class. Here's a basic example of how you might do this:

import Foundation

// Define your custom object
struct CustomObject: Decodable {
    let id: Int
    let name: String
}

// JSON data representing an array of CustomObject
let jsonData = """
[
    {"id": 1, "name": "Object One"},
    {"id": 2, "name": "Object Two"}
]
""".data(using: .utf8)!

// Decode the JSON data
do {
    let decoder = JSONDecoder()
    let objects = try decoder.decode([CustomObject].self, from: jsonData)
    print(objects)
} catch {
    print("Failed to decode JSON: \(error)")
}

In this example, CustomObject is a struct that conforms to Decodable. The JSONDecoder is used to decode a JSON array into an array of CustomObject instances. Make sure your JSON data matches the structure of your custom object.

For more advanced topics related to Swift, such as handling concurrency or performance optimizations, you might find sessions like "Migrate your app to Swift 6" and "Explore Swift performance" from WWDC 2024 helpful. These sessions cover topics like data-race safety and memory layout, which can be crucial when working with complex data structures in Swift.