Last active
November 5, 2019 00:43
-
-
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.
This file contains 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 | |
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