Skip to content

Instantly share code, notes, and snippets.

@ajjames
Created April 21, 2020 22:18
Show Gist options
  • Save ajjames/8c61734fde163de5c32df7c97e9d2294 to your computer and use it in GitHub Desktop.
Save ajjames/8c61734fde163de5c32df7c97e9d2294 to your computer and use it in GitHub Desktop.
SwiftUI Helpers
import Combine
import SwiftUI
struct IfNotNil<Value, Content>: View where Content: View {
private let value: Value?
private let content: (Value) -> Content
init(_ value: Value?,
@ViewBuilder show content: @escaping (Value) -> Content) {
self.value = value
self.content = content
}
var body: some View {
value.map(content)
}
}
struct IfNil<Value, Content: View>: View {
private let bool: Bool?
private let content: Content
init(_ value: Value?,
@ViewBuilder show content: @escaping () -> Content) {
if value == nil {
self.bool = false
} else {
self.bool = nil
}
self.content = content()
}
var body: some View {
bool.map({ _ in content})
}
}
struct If<Value, Content1, Content2>: View where Content1: View, Content2: View {
private let value: Value?
private let content1: (Value) -> Content1
private let content2: Content2
init(notNil value: Value?,
@ViewBuilder show content1: @escaping (Value) -> Content1,
@ViewBuilder elseShow content2: @escaping () -> Content2) {
self.value = value
self.content1 = content1
self.content2 = content2()
}
var body: some View {
ZStack {
IfNil(value) {
self.content2
}
IfNotNil(value) {
self.content1($0)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment