Skip to content

Instantly share code, notes, and snippets.

@apptekstudios
Last active April 20, 2020 11:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apptekstudios/d95634bc24d49fc7bf7d3a561ca64fd5 to your computer and use it in GitHub Desktop.
Save apptekstudios/d95634bc24d49fc7bf7d3a561ca64fd5 to your computer and use it in GitHub Desktop.
Simple Conditional View Closures
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