|
| 1 | +# Idiomatic usage of the Cadova library |
| 2 | + |
| 3 | +## Geometry builders automatically union their children |
| 4 | + |
| 5 | +The `body` property of `Shape2D`/`Shape3D` and the trailing-closure builders of geometry modifier methods (`.subtracting {}`, `.adding {}`, etc.) use `@GeometryBuilder` and automatically union everything they contain. There is no need to wrap children in an explicit `Union {}`. |
| 6 | + |
| 7 | +**Preferred:** |
| 8 | +```swift |
| 9 | +var body: any Geometry3D { |
| 10 | + Box(10) |
| 11 | + Sphere(radius: 6) |
| 12 | +} |
| 13 | +``` |
| 14 | + |
| 15 | +**Avoid:** |
| 16 | +```swift |
| 17 | +var body: any Geometry3D { |
| 18 | + Union { |
| 19 | + Box(10) |
| 20 | + Sphere(radius: 6) |
| 21 | + } |
| 22 | +} |
| 23 | +``` |
| 24 | + |
| 25 | +## Use @GeometryBuilder instead of return statements |
| 26 | + |
| 27 | +When a computed property or method needs to compose geometry, annotate it with `@GeometryBuilder2D` or `@GeometryBuilder3D` instead of using a `return` statement. |
| 28 | + |
| 29 | +**Preferred:** |
| 30 | +```swift |
| 31 | +@GeometryBuilder3D |
| 32 | +var trunk: any Geometry3D { |
| 33 | + Cylinder(radius: 5, height: 20) |
| 34 | + Sphere(radius: 5).translated(z: 20) |
| 35 | +} |
| 36 | +``` |
| 37 | + |
| 38 | +**Avoid:** |
| 39 | +```swift |
| 40 | +var trunk: any Geometry3D { |
| 41 | + return Union { |
| 42 | + Cylinder(radius: 5, height: 20) |
| 43 | + Sphere(radius: 5).translated(z: 20) |
| 44 | + } |
| 45 | +} |
| 46 | +``` |
| 47 | + |
| 48 | +## Prefer .adding {} over explicit Union |
| 49 | + |
| 50 | +When combining a base shape with additional geometry, prefer the `.adding {}` modifier over a standalone `Union {}`. |
| 51 | + |
| 52 | +**Preferred:** |
| 53 | +```swift |
| 54 | +Box(10) |
| 55 | + .adding { |
| 56 | + Sphere(radius: 6).translated(z: 10) |
| 57 | + } |
| 58 | +``` |
| 59 | + |
| 60 | +**Avoid:** |
| 61 | +```swift |
| 62 | +Union { |
| 63 | + Box(10) |
| 64 | + Sphere(radius: 6).translated(z: 10) |
| 65 | +} |
| 66 | +``` |
| 67 | + |
| 68 | +## Don't use Empty() for conditional geometry |
| 69 | + |
| 70 | +Geometry builders support `if` statements directly. An `if` with a false condition outputs nothing — no need to produce an `Empty()` in the else branch. |
| 71 | + |
| 72 | +**Preferred:** |
| 73 | +```swift |
| 74 | +var body: any Geometry3D { |
| 75 | + Box(10) |
| 76 | + if includeHandle { |
| 77 | + Cylinder(radius: 1, height: 20) |
| 78 | + } |
| 79 | +} |
| 80 | +``` |
| 81 | + |
| 82 | +**Avoid:** |
| 83 | +```swift |
| 84 | +var body: any Geometry3D { |
| 85 | + Box(10) |
| 86 | + if includeHandle { |
| 87 | + Cylinder(radius: 1, height: 20) |
| 88 | + } else { |
| 89 | + Empty() |
| 90 | + } |
| 91 | +} |
| 92 | +``` |
0 commit comments