Passing the properties of a struct to a class instance the elegant way

Viewed 52

I have a struct like this:

struct MyStruct: Codable {
  let id: String?
  let item: String?
  let description: String?
  let status: Bool?
}

at some point in code I have to store this on a Core Data entity with the same properties. So I have to do this:

// new core data item
let newItem = MyObject(context: context)
newItem.id = myStruct.id
newItem.item = myStruct.item
newItem.description = myStruct.description
newItem.status = myStruct.status

Now suppose both items have 50 properties. I will have to have 50 of these lines, saving stuff from one side to another.

Is there a more beautiful way to do this?

1 Answers

You can use computed property in your struct which returns a coreData object. For example:

struct MyStruct: Codable {
  let id: String?
  let item: String?
  let description: String?
  let status: Bool?

 func toCoreDataObject() -> MyObject {
     let newItem = MyObject(context: context)
     newItem.id = myStruct.id
     newItem.item = myStruct.item
     newItem.description = myStruct.description
     newItem.status = myStruct.status
     return newItem
   }

}

This way you write the list of 50 properties once in the struct definition, and then call the function as below

let coreDataObject = myStruct.toCoreDataObject()
Related