Unable to modify List inside Realm Object with Swift UI TextField

I’m having trouble updating data inside a Realm Object List using SwiftUI text fields.

The data object contains two strings and two arrays

import RealmSwift

class Course: Object, ObjectKeyIdentifiable {
    @Persisted(primaryKey: true) var _id: ObjectId
    @Persisted var courseName: String
    @Persisted var courseTees: String
    @Persisted var holeYards: List<String>
    @Persisted var holePar: List<String>


My SwiftUI view looks like this

import SwiftUI
import RealmSwift

struct CourseDetailView: View {
    @ObservedRealmObject var course:Course
    var body: some View {
        VStack(alignment: .leading) {
                Text("Course Data:")
            TextField("New course name", text: $course.courseName)
            TextField("TeeMarkers", text: $course.courseTees)
                ForEach(course.holePar.indices, id: \.self) { index in
                    HStack {
                        Text("Hole \(index + 1):") // Adding 1 to start counting from 1
                        TextField("Par", text: $course.holePar[index])
                        TextField("Yards", text: $course.holeYards[index])
        /*.onChange(of: course) {
            // This block will be executed when 'course' is changed.
            // Ensure that you are within a write transaction to modify the Realm object.
            do {
                let realm = try Realm()
                try realm.write {
                    // Update the 'course' object with the modified values
                    realm.add(course, update: .modified)
            } catch {
                print("Error updating course: \(error.localizedDescription)")

I can update the strings directly from a Swift UI TextField. but when I try to do the same with the array, my preview crashes and I get an error saying that I cannot update the Object outside a write transaction.

  1. So updating directly using a binding seems to work with the strings, but not the array.
  2. Adding the commented out block to attempt to write on change doesn’t seem to work either.