> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/ios/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/ios/swiftui/shapes/shape/anyshape.md).

# AnyShape

[SwiftUI](/ios/swiftui.md) ⟩ [shapes](/ios/swiftui/shapes.md) ⟩ [Shape](/ios/swiftui/shapes/shape.md) ⟩ AnyShape&#x20;

{% hint style="success" %}
A [type-erased](/ios/swift/type/erasure.md) shape value. You can use this type to <mark style="color:yellow;">dynamically switch between shape types</mark>.
{% endhint %}

{% tabs %}
{% tab title="💾 程式" %}

```swift
struct MyClippedView: View {

    var isCircular: Bool

    var body: some View {
        ClippedView()
            // ✅ OK (將 Circle 與 Capsule 化為 AnyShape)
            .clipShape(isCircular ? AnyShape(Circle()) : AnyShape(Capsule()))
        ErrorView()
            // 🐞 mismatching types (Circle, Capsule 為不同類型)
            .clipShape(isCircular ? Circle() : Capsule())
    }
}
```

{% endtab %}

{% tab title="⭐️ 重點" %}
官方有 [AnyShape](https://developer.apple.com/documentation/swiftui/anyshape/) 這個型別，估計實作方式可能類似下面：

```swift
import SwiftUI

struct MyAnyShape: Shape {

    private var wrappedShape: any Shape

    init<S: Shape>(_ wrapped: S) {
        self.wrappedShape = wrapped    // ⭐️ 直接儲存 Shape 實例
    }

    // ⭐️ Shape requirement
    func path(in rect: CGRect) -> Path {
        wrappedShape.path(in: rect)
    }
}
```

:point\_right: 參考： [has non-Sendable type](/ios/swift/concurrency/sendable/has-non-sendable-type.md)\
:point\_right: 應用： [view.clipShape()](/ios/swiftui/view/drawing/view.clipshape.md)
{% endtab %}

{% tab title="📘 手冊" %}

* [SwiftUI](https://developer.apple.com/documentation/swiftui) ⟩ [Shapes](https://developer.apple.com/documentation/swiftui/shapes) ⟩ [AnyShape](https://developer.apple.com/documentation/swiftui/anyshape/)&#x20;
  {% endtab %}

{% tab title="👥 相關" %}

* :beginner: [type erasure](/ios/swift/type/erasure.md)
  {% endtab %}

{% tab title="⛔ 錯誤" %}
:lady\_beetle: [has non-Sendable type](/ios/swift/concurrency/sendable/has-non-sendable-type.md)

:lady\_beetle: [mismatching types](/ios/swiftui/view/drawing/view.clipshape/mismatching-types.md)
{% endtab %}
{% endtabs %}
