UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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
    }
  }
}

1      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.