Conditional View Modifiers in SwiftUI

September 2, 2020 • 08: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 weekly updates on this blog. No spams — I promise.

Blog Posts Archive