Skip to content

Instantly share code, notes, and snippets.

@danielctull
Last active November 5, 2019 00:43
Show Gist options
  • Save danielctull/ded2b57e0bc71b8c97a8ab55ac412c31 to your computer and use it in GitHub Desktop.
Save danielctull/ded2b57e0bc71b8c97a8ab55ac412c31 to your computer and use it in GitHub Desktop.
A view which takes a value and shows one view or another depending on whether the value is nil or not.
import SwiftUI
public struct UnwrapView<Some: View, None: View>: View {
private let some: () -> Some?
private let none: () -> None?
public init<Value>(value: Value?,
some: @escaping (Value) -> Some,
none: @escaping () -> None) {
self.some = { value.map(some) }
self.none = { value == nil ? none() : nil }
}
public var body: some View {
Group {
some()
none()
}
}
}
struct UnwrapView_Previews: PreviewProvider {
static var previews: some View {
Group {
UnwrapView(value: "Some",
some: Text.init,
none: { Color.red })
.previewLayout(.fixed(width: 200, height: 50))
.previewDisplayName("some")
UnwrapView(value: nil,
some: Text.init,
none: { Color.red })
.previewLayout(.fixed(width: 200, height: 50))
.previewDisplayName("none")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment