Skip to content

Instantly share code, notes, and snippets.

@onmyway133
Last active April 4, 2022 05:25
Show Gist options
  • Save onmyway133/3f54accb680b47cff571f921e3718b16 to your computer and use it in GitHub Desktop.
Save onmyway133/3f54accb680b47cff571f921e3718b16 to your computer and use it in GitHub Desktop.
ShapeBuilder
import SwiftUI
struct ContentView: View {
var value: Int = 0
var body: some View {
Text("Hello")
.padding()
.background(.orange)
.clipShape(shape)
}
@ShapeBuilder
var shape: some Shape {
switch value {
case 0: Circle()
case 1: Rectangle()
default: Ellipse()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
@resultBuilder
public enum ShapeBuilder {
public static func buildBlock<S: Shape>(_ builder: S) -> some Shape {
builder
}
static func buildOptional<S: Shape>(_ component: S?) -> EitherShape<S, EmptyShape> {
component.flatMap(EitherShape.first) ?? EitherShape.second(EmptyShape())
}
static func buildEither<First: Shape, Second: Shape>(first component: First) -> EitherShape<First, Second> {
.first(component)
}
static func buildEither<First: Shape, Second: Shape>(second component: Second) -> EitherShape<First, Second> {
.second(component)
}
}
public enum EitherShape<First: Shape, Second: Shape>: Shape {
case first(First)
case second(Second)
public func path(in rect: CGRect) -> Path {
switch self {
case let .first(first):
return first.path(in: rect)
case let .second(second):
return second.path(in: rect)
}
}
}
public struct EmptyShape: Shape {
public init() {}
public func path(in rect: CGRect) -> Path {
Path()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment