Created
June 12, 2019 22:43
-
-
Save darknoon/b5e54c2ce5b211dc717c37061a47f09f to your computer and use it in GitHub Desktop.
How to create a View that renders different content based on enum cases in Swift UI
This file contains hidden or 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
enum Block { | |
case h(title: String) | |
case p(body: String) | |
} | |
extension View { | |
func erased() -> AnyView { | |
return AnyView(self) | |
} | |
} | |
extension Block : View { | |
var body: AnyView { | |
switch self { | |
case let .h(title): | |
return | |
HeadingView(title: title) | |
.erased() | |
case let .p(body): | |
return | |
ParagraphView(text: body) | |
.erased() | |
} | |
} | |
} | |
struct CardContentView : View { | |
let content: Content | |
var body: some View { | |
VStack(alignment: .leading) { | |
ForEach(content.body) {item in | |
item | |
} | |
} | |
.padding([.leading, .bottom, .trailing]) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment