-
Newbie Q: Is there a straightforward way in Swift to duplicate an existing record? I know I could do this in SQL, but I'm interested in having a record type clone itself with the clone having a new unique ID. |
Beta Was this translation helpful? Give feedback.
Answered by
groue
Feb 18, 2025
Replies: 1 comment 1 reply
-
Hello @bradhowes, If your record has an auto-incremented id, you can duplicate a record this way: struct Player: Codable {
var id: Int64?
var name: String
var score: Int
}
extension Player: FetchableRecord, MutablePersistableRecord {
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
try dbQueue.write { db in
// Fetch player 42
let player = try Player.find(db, key: 42)
// Duplicate with a new id
var copy = player
copy.id = nil
try copy.insert(db)
print(copy.id) // Some id which is not 42
} If the id is not auto-incremented, you can duplicate a record as below: struct Player: Codable, Identifiable {
var id: String
var name: String
var score: Int
}
extension Player: FetchableRecord, PersistableRecord { }
try dbQueue.write { db in
// Fetch player "foo"
let player = try Player.find(db, id: "foo")
// Duplicate into player "bar"
var copy = player
copy.id = "bar"
try copy.insert(db)
} |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
bradhowes
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello @bradhowes,
If your record has an auto-incremented id, you can duplicate a record this way:
If the id is not auto-incremented, you can duplicate a record as below: