Skip to content

Instantly share code, notes, and snippets.

@mariia-cherniuk
Last active May 27, 2020 15:24
Show Gist options
  • Save mariia-cherniuk/64161e3548edb7077488c904a790193b to your computer and use it in GitHub Desktop.
Save mariia-cherniuk/64161e3548edb7077488c904a790193b to your computer and use it in GitHub Desktop.
Nice little utility view that allows you handle optional values in your SwiftUI views
import SwiftUI
@available(iOS 13.0, *)
public struct IfLetElseView<Value, IfContent: View, ElseContent: View>: View {
private let value: Value?
private let ifContent: (Value) -> IfContent
private let elseContent: () -> ElseContent
public init(_ value: Value?,
@ViewBuilder ifContent: @escaping (Value) -> IfContent,
@ViewBuilder elseContent: @escaping () -> ElseContent) {
self.value = value
self.ifContent = ifContent
self.elseContent = elseContent
}
public var body: some View {
Group<_ConditionalContent<IfContent, ElseContent>> {
if let value = value {
return ViewBuilder.buildEither(first: self.ifContent(value))
} else {
return ViewBuilder.buildEither(second: self.elseContent())
}
}
}
}
#if DEBUG
@available(iOS 13.0, *)
public struct IfLetElseView_Previews: PreviewProvider {
public static var previews: some View {
IfLetElseView("🐈", ifContent: { (text) in
Text("Congratulations, you got a \(text)")
}) {
Text("Better luck next time 😿")
}.previewLayout(.sizeThatFits)
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment