How do I link structs? Need to optimise performance

Viewed 66

I am trying to optimise my code to minimise the download size of unnecessary information.

My objective is to link items in the testData array to call methods from another struct.

Here is an example:

struct Recipe: Identifiable, Hashable, Codable {
    @DocumentID var id: String? = UUID().uuidString
    var title: String
    var description: String
    var imageName: String
}
let testData = [
    Recipe(title: "Recipe1", description: "Description1", imageName: "Image1"
    Recipe(title: "Recipe2", description: "Description2", imageName: "Image2"
    Recipe(title: "Recipe3", description: "Description3", imageName: "Image3"
]

// Then another struct, which needs to be linked to members of the array above
// Code below is incorrect, will not work
struct CommentSection {
    var recipe: Recipe // would I link a variable to struct here or how else to proceed?
    var user: String
    var body: String
}
let commentData [
    CommentSection(user: "User1", body: "body1"
    CommentSection(user: "User1", body: "body1"
]

What I would like to do is to be able to associate items within CommentSection with items in the testData array without making a substruct.

I know that classes can inherit, although have much of the app tied in the the struct I.E database, arrays, etc. therefore would like to keep it a struct.

How would I proceed to call CommentSection.user & body which should be linked to [#] of testData without accessing it through the Recipe struct?

1 Answers

I'm not sure what you want to do. But, first of all: a comment should be linked to the object being commented - it should look like this:

struct CommentedObject {
    ...
}

struct Comment {
    ...
    let ownerId, commentedObjectId: String
    ...
}

where: ownerId - commentator id, commentedObjectId - id of the commented object,

Second:

@DocumentID var id: String? = UUID().uuidString

should look like this - @DocumentID var id: String? – Firebase automatically creates an ID when an object is initialized, don't forget about a CodingKeys enum.

Related