n savoini
n savoini

Reputation: 552

Swift Codable Design

I have a "design" issue with my application and the use of Codable.

I'm managing Horses, Instructors and Classes. I'm using an array of horses, an array of instructors, and an array of classes ( referencing horses and instructors), all as variables.

Now i'm looking to have it in one Library object, and use Codable on this object.

I just created a Library Class with an array of each inside. I can load a JSON file fine and all array are filled except i'm loosing the references for horses and instructors.

When i load the classes, if it has an horse associated a new object is created, it doesn't take the reference to the horse already loaded.

Class Library :

class Library : Codable {

var name:String=""

// Instructors
var instructors:[Instructor] = [Instructor]()

// Horses
var horses:[Horse] = [Horse]()

// Courses
var courses:[Course] = [Course]()}

Class Course :

class Course : Codable {

var id:Int

var date:Date

var horse:Horse?

var instructor:Instructor?}

Any idea how to resolve my issue ?

I'm not especially looking for the technical answer, but how would you resolve this issue ;)

Thanks, Nicolas

Upvotes: 2

Views: 130

Answers (1)

dktaylor
dktaylor

Reputation: 914

The easiest solution is to implement Decodable explicitly and set the properties of the class objects to the references to the horse and instructor objects in the library. This would add the following to the Library class:

enum CodingKeys: String, CodingKey {
        case name
        case instructors
        case horses
        case courses
    }

init(from decoder: Decoder) throws {
    let values = try decoder.container(keyedBy: CodingKeys.self)
    name = try values.decode(Double.self, forKey: .name)
    instructors = try values.decode(Double.self, forKey: .instructors)
    horses = try values.decode(Double.self, forKey: .horses)
    courses = try values.decode(Double.self, forKey: .courses)

    for course in courses {
        for hourse in horses {
            if(course.horse.id == horse.id){
                course.horse = horse
                break
            }
        }
        for instructor in insturctors{
            if(course.instructor.id == instructor.id){
                course.instructor = instructur
                break
            }
        }
    }
}

Upvotes: 1

Related Questions