Skip to content

Instantly share code, notes, and snippets.

@ryanlintott
Last active March 4, 2025 15:50
Show Gist options
  • Save ryanlintott/0e59e60cff813babc42ca0e6ac7b3221 to your computer and use it in GitHub Desktop.
Save ryanlintott/0e59e60cff813babc42ca0e6ac7b3221 to your computer and use it in GitHub Desktop.
A conditional SwiftUI view extension that can be used to optionally apply view modifiers based on OS availability. Learn more about how it works here: https://youtu.be/mgplcrJh0K0?si=YNz0IVSiN-3myb08
import SwiftUI
extension View {
/// Applies the given transform or returns the untransformed view.
///
/// Useful for availability branching on view modifiers. Do not branch with any properties that may change during runtime as this will cause errors.
/// - Parameters:
/// - transform: The transform to apply to the source `View`.
/// - Returns: The view transformed by the transform.
@ViewBuilder
func ifAvailable(@ViewBuilder _ transform: (Self) -> (some View)?) -> some View {
if let transformed = transform(self) { transformed } else { self }
}
}
struct ExampleView: View {
var body: some View {
Image(systemName: "heart")
.resizable()
.scaledToFit()
.ifAvailable {
/// Only use if #availalbe branching inside to ensure no runtime changes
if #available(iOS 17, *) {
$0.symbolEffect(.bounce.down, value: value)
}
/// If this closure returns nil it will return the view unmodified
}
}
}
@ryanlintott
Copy link
Author

I've updated the code based on a suggestion from Jessy Catterwaul. (Thanks!)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment