List{// ⚠️ ALWAYS freeze a Realm list while // iterating in a SwiftUI View's ForEach(). // Otherwise, unexpected behavior will occur,// especially when deleting object from the list.ForEach(items.freeze()){ frozenItem in// "Thaw" the item before passing it in, as ItemRow// may want to edit it, and // cannot do so on a frozen object.// This is a convenient place // to thaw because we have access// to the unfrozen realm via the items list.ItemRow(item: items.realm!
.resolve(ThreadSafeReference(to: frozenItem))!)}.onDelete(perform: delete)// swipe to delete action.onMove(perform: move)// move items in editing mode}
Delete an item
// Deletes the given item.func delete(at offsets:IndexSet){
guard let realm = items.realm else{
items.remove(at: offsets.first!)return}try! realm.write{
realm.delete(items[offsets.first!])}}
Add/update item name (ItemDetailsView.swift)
// Ensure the item was thawed before passing ininit(_ item:Item){assert(!item.isFrozen)}
// Whenever a user performs an action // like pressing the return key, // TextField calls onCommit closureTextField(item.name, text: $newItemName, onCommit:{self.commit()})
// Writes the given name to the realm in a transaction.privatefunc commit(){
guard let realm = item.realm else{
item.name = newItemName
return}try! realm.write{
item.name = newItemName
}}
Toggle favorite (ItemDetailsView.swift)
// ⚠️ We cannot use the item property // directly, as sets will not// automatically run in a transaction. // Here we provide a custom// binding to handle the update in a transaction.Toggle(isOn:Binding(get:{// Return the value as normal.
item.isFavorite
}, set:{(value)in// If the item is associated with a realm,// open a transaction on it in order to do// the write.
guard let realm = item.realm else{
item.isFavorite = value
return}try! realm.write{
item.isFavorite = value
}})){// 💡 It might have been nice to use a Button instead// of a Toggle, but that wouldn't demonstrate custom bindings.Image(systemName: item.isFavorite ? "heart.fill":"heart")}