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 {
	func `if`<Transform: View>(
		_ condition: Bool,
		transform: (Self) -> Transform
	) -> some View {
		if condition {
		} else {

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 {
			.if(X) { $0.padding(8) }
			.if(Y) { $0.background( }

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