The toggle switch in SwiftUI unfortunately has no „action“ event like the button. If you enter a function call in the curly brackets, you will get the following error message:
Static method ‚buildBlock‘ requires that ‚String‘ conform to ‚View‘
The trick is to create a view here.

In the example code you will find the line:
Text("Toggle \(ToggleAction(State: showResubmission))")
That’s solution. Take the ToggleAction function and expand it for your purposes. In this example, the status variable is simply entered as return value.
// // ContentView.swift // ToggleSwitchActionDemo // // Created by T. Stephan on 22.02.20. // Copyright © 2020 eCommerce - Tobias Stephan. All rights reserved. // import SwiftUI import Combine class MainClass: ObservableObject { public var ToggleSwitchState = false init(){ } } struct ContentView: View { @ObservedObject var oMainClass = MainClass() @State private var showResubmission = false var body: some View { Toggle(isOn: $showResubmission){ Text("Toggle \(ToggleAction(State: showResubmission))") .padding() } } func ToggleAction(State: Bool) -> String { if (State != oMainClass.ToggleSwitchState) { oMainClass.ToggleSwitchState = State //do something else... print("Toggle switched...") } return String(State) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }

Über den Autor