UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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


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



yes this is very good


Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

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.