TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.