I’m building a to do list app to learn SwiftData and wondering how I manage the order of bullets added to the array. When I add a bullet it gets a random index.
Lets say theres 10 bullets in the array. The user selects bullet 4 and wants to add a bullet underneath it (where bullet 5 currently is) How do I make sure the new bullet gets an index of 5 and the bullets after get assigned new indices? So the order of the bullets persists? Obviously has to be managed properly to be sure no bullets get assigned the same number.
Or say the user drags a bullet object to reorder the list.
Is the only way to have a middle layer that saves all the bullets in proper order when the array is modified?
@Model
final class List: Identifiable {
let id: UUID
var index: Int?
var color: String
var title: String
var createdAt: Date // Added createdAt property
@Relationship(deleteRule: .cascade)
var bullets: [Bullet]?
// Calculating height based on the number of bullets
var height: CGFloat {
return CGFloat(50 + (bullets?.count ?? 0) * 15)
}
init(index: Int? = nil, color: String, title: String, bullets: [Bullet] = []) {
self.id = UUID()
self.index = index
self.color = color
self.title = title
self.bullets = bullets
self.createdAt = Date() // Initialize createdAt with current date and time
}
}
@Model
class Bullet: Identifiable {
let id: UUID
var text: String
var state: Bool
var createdAt: Date // Added createdAt property
init(text: String, state: Bool = false) {
self.id = UUID()
self.text = text
self.state = state
self.createdAt = Date() // Initialize createdAt with current date and time
}
}
1