Skip to content

Swift Way to Duplicate a Record #1725

Answered by groue
bradhowes asked this question in Q&A
Discussion options

You must be logged in to vote

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: St…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@bradhowes
Comment options

Answer selected by bradhowes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants