NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

Do TextFields and Toggles always update their bound property on the MainActor?

Forums > 100 Days of SwiftUI

If I have an app that uses TextFields or Toggles where I try am trying to implement MVVM (example below) it doesn't give me any of the purple errors saying "Publishing changes from within view updates is not allowed, this will cause undefined behavior."

Does this mean that TextField and Toggle Views always update their bound property on the main actor? Or is it just something that the compiler doesn't detect, but could still cause an error somehow?

ContentView.swift

import SwiftUI

struct ContentView: View {
  @StateObject var viewModel = ViewModel(name: "", likes: true, food: "")

  var body: some View {
    Form {
      TextField("Name", text: $viewModel.name)
      Toggle(viewModel.likes ? "Likes" : "Dislikes", isOn: $viewModel.likes)
      TextField("Food", text: $viewModel.food)
      Text("\(viewModel.name) \(viewModel.likes ? "Likes" : "Dislikes") \(viewModel.food)")
    }
  }
}

ContentView-ViewModel.swift

import Foundation

extension ContentView {
  @MainActor class ViewModel: ObservableObject {
    @Published var name: String
    @Published var likes: Bool
    @Published var food: String

    init(name: String, likes: Bool, food: String) {
      self.name = name
      self.likes = likes
      self.food = food
    }
  }
}

   

Hacking with Swift is sponsored by MadMachine

SPONSORED Want to explore your Swift skill outside of the Apple world? Join the MadMachine community and start to program microcontrollers in Swift.

Get it now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.