The most common solution is to define a new
if
View
extension:extension View { @ViewBuilder func `if`<Transform: View>( _ condition: Bool, transform: (Self) -> Transform ) -> some View { if condition { transform(self) } else { self } } }
This function will apply
transform
to our view whencondition
istrue
, otherwise it will leave the original view untouched.Going back to our example, this is one way to use it:
struct MyView: View { var body: some view { myView .if(X) { $0.padding(8) } .if(Y) { $0.background(Color.blue) } } }
This is perfect.
Source: fivestars.blog