Search code examples
swiftuiviewbuilder

How to execute non-view code inside a SwiftUI view


I have been struggling with this over and over again, so I think I'm missing something. I need to do math, make a setting, assign a value or any of a host of simple operations in reaction to some user action, such as the example shown here, and SwiftUI is wanting a View where I don't need a view. There's got to be a way around the ViewBuilder's rules. I kind of worked around this by creating an unnecessary view and executing the code I need inside the View's init(), but that seems terribly awkward.

import SwiftUI

struct ContentView: View
{
    @State var showStuff = false

    var body: some View
    {
        VStack
        {
            Toggle(isOn: $showStuff)
            {
                Text("Label")
            }
            if showStuff
            {
                UserDefaults.standard.set(true, forKey: "Something")
            }
        }
    }
}

Solution

  • I think the best way to do this now is using onChange(of:perform:) modifier, for iOS14.0+

    These simple executions (like do math, assign a value) are nothing but actions in swift terminology, which should be performed after touching any UI element because swiftUI is declarative. In your case, you can use this with any View type. Other similar options are .onAppear() or .onDisappear() (self-explanatory).

    Surprisingly, apple documentation for these are actually good and elaborate.

    Link - https://developer.apple.com/documentation/swiftui/view/onchange(of:perform:)