Skip to content

Instantly share code, notes, and snippets.

@liscio
Forked from ishabazz/SwiftUILunch
Created June 26, 2020 17:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liscio/db0da7d9628b07840543e130165b025d to your computer and use it in GitHub Desktop.
Save liscio/db0da7d9628b07840543e130165b025d to your computer and use it in GitHub Desktop.
Trying to figure out how to show derived Views from different data types.
//: A UIKit based Playground for presenting user interface
import UIKit
import PlaygroundSupport
import SwiftUI
enum ComponentType{
case sandwich
case smoothie
case soup
}
class Component: Identifiable, Hashable {
static func == (lhs: Component, rhs: Component) -> Bool {
return lhs.id == rhs.id
}
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
var order:UInt
let type:ComponentType
let id:String
init(type:ComponentType, order:UInt = 0, id:String = UUID().uuidString){
self.type = type
self.order = order
self.id = UUID().uuidString
}
func view() -> some View{
Text("Default")
}
}
class SandwichComponent: Component{
init(order:UInt = 0){
super.init(type: .sandwich)
}
}
class SoupComponent: Component{
init(order:UInt = 1){
super.init(type: .soup, order: order)
}
}
class SmoothieComponent: Component{
init(order:UInt = 0){
super.init(type: .smoothie)
}
}
struct SandwichView: View {
let component: SandwichComponent
var body: some View {
Text("Sandwich, order \(component.order)")
}
}
struct SoupView: View {
let component: SoupComponent
var body: some View {
TextField("Placeholder", text: .constant("SOUP order \(component.order)!!!!"))
}
}
struct SmoothieView: View {
let component: SmoothieComponent
var body: some View {
Image(systemName: "heart")
}
}
struct LunchList:View {
var items:[Component] = [SandwichComponent(),SmoothieComponent(),SoupComponent()]
var body: some View{
VStack{
List {
ForEach(items,id:\.self){ item in
switch item.type {
case .sandwich:
// SandwichView(component: item as! SandwichComponent)
(item as? SandwichComponent).map(SandwichView.init(component:))
case .soup:
SoupView(component: item as! SoupComponent)
case .smoothie:
SmoothieView(component: item as! SmoothieComponent)
}
}
}
}
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.setLiveView(LunchList())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment