Reputation: 3427
Whenever I try to persist an object to the DB using insert
or upsert
, Xcode complains Cannot use mutating member on immutable value
.
I understand why Xcode is complaining, but do I really have to make a copy of the function parameter just to save? It seems so hacky. Perhaps there's a better way?
static func saveWorkoutTemplate(wt: WorkoutTemplate) {
guard let dbQueue = openDB() else { return }
var w = wt //lame hack
try! dbQueue.write { db in
try! w.upsert(db) // this works
//try! wt.upsert(db) // error: Cannot use mutating member on immutable value: 'wt' is a 'let' constant
}
}
Upvotes: 2
Views: 117
Reputation: 299275
Yes, the thing you've marked "lame hack" is correct. It's not a hack. It's being explicit about what you want to happen. You're making a local copy that does not modify the thing that was passed in.
But I don't need whatever changes upsert is making to persist outside of the function.
And that's exactly why you need to make a copy. Most large types employ copy-on-write to ensure that the copy is as cheap as possible. In this case, the optimizer will likely eliminate the copy entirely. But you will still be clear about what's going on.
Upvotes: 1