Last active
April 20, 2020 11:52
-
-
Save apptekstudios/d95634bc24d49fc7bf7d3a561ca64fd5 to your computer and use it in GitHub Desktop.
Simple Conditional View Closures
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 | |
@ViewBuilder | |
func `ifLet`<T, Content: View>(_ optional: T?, @ViewBuilder builder: ((T) -> Content)) -> some View { | |
optional.map(builder) | |
} | |
@ViewBuilder | |
func `ifNotLet`<T, Content: View>(_ optional: T?, @ViewBuilder builder: (() -> Content)) -> some View { | |
if optional == nil { | |
builder() | |
} | |
} | |
func `ifLet`<T, Content: View>(_ optional: T?, @ViewBuilder builder: ((T) -> Content)) -> IfLetPartialResult<T, Content> { | |
IfLetPartialResult(optional, builder) | |
} | |
struct IfLetPartialResult<Wrapped, A: View> { | |
var a: A? | |
init(_ optional: Optional<Wrapped>, @ViewBuilder _ a: (Wrapped) -> A) { | |
self.a = optional.map(a) | |
} | |
@ViewBuilder | |
func `else`<B: View>(@ViewBuilder _ b: () -> B) -> some View { | |
if a != nil { | |
a | |
} else { | |
b() | |
} | |
} | |
} | |
let x: String = "TEST" | |
var result: some View { | |
ifLet(x) { | |
Text($0) | |
}.else { | |
Image(systemName: "paperplane") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment