Skip to content

Instantly share code, notes, and snippets.

@eldaroid
Last active October 7, 2024 19:01
Show Gist options
  • Save eldaroid/3511f616d1b59eac9e93eea21fee4f02 to your computer and use it in GitHub Desktop.
Save eldaroid/3511f616d1b59eac9e93eea21fee4f02 to your computer and use it in GitHub Desktop.
RU: Этот код расширяет протокол View в SwiftUI, предоставляя методы для условного применения модификаторов к представлениям на основе булевых и опциональных значений. EN: This code extends the View protocol in SwiftUI, providing methods for conditionally applying modifiers to views based on boolean and optional values
import SwiftUI
// Extension to handle boolean conditions
extension View {
@ViewBuilder
public func `if`<Transform: View>(
_ value: Bool,
transform: (Self) -> Transform
) -> some View {
if value {
transform(self)
} else {
self
}
}
@ViewBuilder
public func `if`<TrueContent: View, FalseContent: View>(
_ value: Bool,
if ifTransform: (Self) -> TrueContent,
else elseTransform: (Self) -> FalseContent
) -> some View {
if value {
ifTransform(self)
} else {
elseTransform(self)
}
}
}
// Extension to handle optional values with true/false branches
extension View {
@ViewBuilder
public func ifLet<V, TrueContent: View, FalseContent: View>(
_ value: V?,
if ifTransform: (Self, V) -> TrueContent,
else elseTransform: (Self) -> FalseContent
) -> some View {
if value != nil {
ifTransform(self, value!)
} else {
elseTransform(self)
}
}
}
// Extension to handle optional values (if-let)
extension View {
@ViewBuilder
public func ifLet<V, Transform: View>(
_ value: V?,
transform: (Self, V) -> Transform
) -> some View {
if value != nil {
transform(self, value!)
} else {
self
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment