Last active
January 7, 2021 13:15
-
-
Save darrarski/f3886d4d0a3598132a3fdd62b3061eb2 to your computer and use it in GitHub Desktop.
SwiftUI IfLet helper functions
This file contains hidden or 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 | |
func IfLet<T, ThenOut: View>( | |
_ value: T?, | |
then: (T) -> ThenOut | |
) -> some View { | |
ViewBuilder.buildIf(value.map { then($0) }) | |
} | |
func IfLet<T, ThenOut: View, ElseOut: View>( | |
_ value: T?, | |
then: (T) -> ThenOut, | |
`else`: () -> ElseOut | |
) -> some View { | |
value.map { ViewBuilder.buildEither(first: then($0)) } | |
?? ViewBuilder.buildEither(second: `else`()) | |
} |
one more way
func ifLet<T, V>(_ value: T?, then: (T) -> V) -> V? where V: View {
value.map(then)
}
let optionalString: String? = "swift"
var body: some View {
optionalString.map { string in
Text(string)
}
}
Which is a quote of my code from here :P https://forums.swift.org/t/how-to-set-default-clouse-param-in-view-method/33815/5
Oops, I didn't notice))
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
it can be done with modifierIf