A Library that makes SwiftUI conditional statements easy
This method applies the given transform if the given condition evaluates to true.
Text("Hello, World!")
.if(someCondition) { view in
view
.foregroundColor(.red)
.background(Color.yellow)
}
same with .if
but with else
Text("Hello, World!")
.if(someCondition) { view in
view
.foregroundColor(.red)
.background(Color.yellow)
}, else: { view in
view
.foregroundColor(.blue)
}
same with if, but it takes an optional value instead of a boolean and unwraps it
struct ContentView: View {
@State private var color: Color? = nil
var body: some View {
Text("Hello World")
.ifLet(color) { color, view in
view
.foregroundColor(color)
}
}
}
same with .ifLet
but with else
struct ContentView: View {
@State private var color: Color? = nil
var body: some View {
Text("Hello World")
.ifLet(color) { color, view in
view
.foregroundColor(color)
}, else: { view in
view
.foregroundColor(.red)
}
}
}
this method extracts the view like in the .if
statement, especially useful when using if #available()
statement
Toggle("I'm a conditionally modified Toggle!", isOn: .constant(true))
.extractView { view in
Group {
if #available(iOS 15.0, *) {
view
.tint(.indigo)
}
else {
view
.toggleStyle(SwitchToggleStyle(tint: .init(.systemIndigo)))
}
}
}
This implementaion is not new, and it's been used widely for the time being, but be aware that it could cause you some trouble with animations, as described in this article, so be cautious about it when using this library.