Conditional View Modifiers in SwiftUI

September 2, 2020 • 8:59 AM

Federico Zanetello:

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 when condition is true, 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.

Let’s stay in touch!

Sign up for the weekly updates of anything that appears on this blog. You will read about my outdoor life around British Columbia, technical discussions as a Data Analyst & App Developer, as well as other random discoveries and thoughts.

Blog Posts Archive