Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")
            }
        }
    }
}
like image 870
Russ Avatar asked Feb 04 '26 04:02

Russ


1 Answers

Way 1 (best):

struct ExecuteCode : View {
    init( _ codeToExec: () -> () ) {
        codeToExec()
    }
    
    var body: some View {
        EmptyView()
    }
}

usage:

HStack {
    ExecuteCode { 
        print("SomeView1 was re-drawn!")
        print("second print")
    }

    SomeView1()
}

Way 2:

( my first way is better - you're able to write only simple code here )

HStack {
    // `let _ =` works inside of View!
    let _ = print("SomeView1 was re-drawn!") 

    SomeView1()
}

Way 3:

( +- the same situation as in first way. Good enough solution. )

HStack {
    let _ = { // look here. "let _ =" is required
        print("SomeView1 was re-drawn!")
        print("second print")
    }() // look here. "()" is also required
    
    SomeView1()
}

But other dev's possibly can not understand this code (especially if it is large), so first one is a little bit better.

like image 150
Andrew Avatar answered Feb 12 '26 17:02

Andrew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!