Assertions in View bodies

I would like to be able to write something like:

struct FooView: View
{
    let foo: Foo;

    var body: some View {
        assert(foo.valid);
        ......
    }
};

but of course I can't, because "Type () cannot conform to View".

What's the best way to achieve this?

Answered by VAndrJ in 820685022

You can use let _ syntax. Example:

    var body: some View {
        let _ = assert(foo.valid)
        ......
    }

I would do it in onAppear:

struct Foo {
    var valid : Bool
}

struct FooView: View {
    var foo: Foo = Foo(valid: false)

    var body: some View {
        Text("Check assert")
            .onAppear() {
                assert(foo.valid)
            }
    }
}

Other option is to do it in init()

Accepted Answer

You can use let _ syntax. Example:

    var body: some View {
        let _ = assert(foo.valid)
        ......
    }

You can use let _ syntax.

Thanks, that's what I was thinking of.

(I wonder what would need to change in the resultBuilder stuff to make this work without the extra noise?)

Assertions in View bodies
 
 
Q