Skip to content

Instantly share code, notes, and snippets.

@codelynx
Created January 29, 2024 06:48
Show Gist options
  • Save codelynx/d3520b55acf4baf7ed5a61738efb4839 to your computer and use it in GitHub Desktop.
Save codelynx/d3520b55acf4baf7ed5a61738efb4839 to your computer and use it in GitHub Desktop.
This code demonstrate how to make concrete inspector-like view from abstract protocol.
// Swift 5.9
//
// Following code demonstrate how to implemnt inspector-like view from abstruct protocol.
// Somehow, @Binding will not work in this case under Swift 5.9
import SwiftUI
protocol Shape {
func view() -> AnyView
}
class CircleModel: ObservableObject, Shape {
@Published var count = 0
func view() -> AnyView {
AnyView(CircleView(circleModel: self))
}
}
class RectangleModel: ObservableObject, Shape {
@Published var count = 0
func view() -> AnyView {
AnyView(RectangleView(rectangleModel: self))
}
}
struct CircleView: View {
@ObservedObject var circleModel: CircleModel
var body: some View {
Text("Circle: count=\(circleModel.count)")
Button("count") {
circleModel.count += 1
}
}
}
struct RectangleView: View {
@ObservedObject var rectangleModel: RectangleModel
var body: some View {
Text("Rectangle: count=\(rectangleModel.count)")
Button("count") {
rectangleModel.count += 1
}
}
}
struct ShapeEditorView<S: Shape & ObservableObject>: View {
@ObservedObject var shape: S
var body: some View {
shape.view()
}
}
struct ShapeView: View {
@StateObject var shape = CircleModel()
var body: some View {
ShapeEditorView(shape: shape)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment