Created
August 28, 2020 06:34
-
-
Save kylehughes/6e1a57ea66bd7a0b8d97ef1da9dbc603 to your computer and use it in GitHub Desktop.
SwiftUI: Conditionally Configuring Views
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
public extension View { | |
// MARK: Conditionally Configuring Views | |
@ViewBuilder func `if`<TrueView>( | |
_ condition: Bool, | |
transform: (Self) -> TrueView | |
) -> some View where TrueView: View { | |
if condition { | |
transform(self) | |
} else { | |
self | |
} | |
} | |
@ViewBuilder func `if`<TrueView, FalseView>( | |
_ condition: Bool, | |
true trueTransform: (Self) -> TrueView, | |
else falseTransform: (Self) -> FalseView | |
) -> some View where TrueView: View, FalseView: View { | |
if condition { | |
trueTransform(self) | |
} else { | |
falseTransform(self) | |
} | |
} | |
@ViewBuilder func ifLet<Value, TrueView>( | |
_ value: Value?, | |
transform: (Self, Value) -> TrueView | |
) -> some View where TrueView: View { | |
if let value = value { | |
transform(self, value) | |
} else { | |
self | |
} | |
} | |
@ViewBuilder func ifLet<Value, TrueView, FalseView>( | |
_ value: Value?, | |
true trueTransform: (Self, Value) -> TrueView, | |
else falseTransform: (Self) -> FalseView | |
) -> some View where TrueView: View, FalseView: View { | |
if let value = value { | |
trueTransform(self, value) | |
} else { | |
falseTransform(self) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment