BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

SwiftData: How to make a copy of a model containing an array of other models

Forums > SwiftUI

In SwiftData I have a @Model class for a log. This has a name and some other attributes, but most importantly an array of LogEntry. Log Entries are also @Model class. So:

@Model class Log { var name: String = "" ... @Relationship(inverse: \LogEntry.log) var logEntries: [LogEntry] = [] }

@Model class LogEntry { var name: String = "" ... var log : Log? = nil }

My question is: How do I make a complete copy of a log? I'd like to be able to write:

var log = Log(name: "Log 1", [ LogEntry(name: "Log Entry 1"), LogEntry(name: "Log Entry 2") ] ) modelContext.insert(log)

and then somewhere later: var logCopy = Log(basedOnLog: log) And this new object should also contain a copy of all log entries in its logEntries array.

To be honest, I feel a little stupid. Because deep copying a class I have basically learned back in the C/C++ days some decades ago. But I am really stuck here. Any help is highly appreciated! How does the initializer or a copy function look like so that it works in SwiftData?

Thanks a lot!

Kind regards Stefan

2      

Suppose this article will answer your question. Not sure if it works with @Model though... but give it a try.

https://www.hackingwithswift.com/example-code/system/how-to-copy-objects-in-swift-using-copy

2      

yes this is very good

2      

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.