# AnyShape

[SwiftUI](https://lochiwei.gitbook.io/ios/swiftui) ⟩ [shapes](https://lochiwei.gitbook.io/ios/swiftui/shapes) ⟩ [Shape](https://lochiwei.gitbook.io/ios/swiftui/shapes/shape) ⟩ AnyShape&#x20;

{% hint style="success" %}
A [type-erased](https://lochiwei.gitbook.io/ios/swift/type/erasure) 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](https://lochiwei.gitbook.io/ios/swift/concurrency/sendable/has-non-sendable-type "mention")\
:point\_right: 應用： [view.clipshape](https://lochiwei.gitbook.io/ios/swiftui/view/drawing/view.clipshape "mention")
{% 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: [erasure](https://lochiwei.gitbook.io/ios/swift/type/erasure "mention")
  {% endtab %}

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

:lady\_beetle: [mismatching-types](https://lochiwei.gitbook.io/ios/swiftui/view/drawing/view.clipshape/mismatching-types "mention")
{% endtab %}
{% endtabs %}
