首页 > 解决方案 > 形状的条件创建 - SwiftUI

问题描述

我正在尝试编写一个根据指定条件创建形状但出现编译错误的函数。

func createShape() -> some Shape {
    switch self.card.shape {
    case .oval:
        return Capsule()
    case .rectangle:
        return Rectangle()
    case .circe:
        return Circle()
    default:
        return Circle()
    }
}

我得到的错误:

函数声明了一个不透明的返回类型,但其主体中的返回语句没有匹配的底层类型

标签: swiftuishapes

解决方案


在这篇文章的帮助下,对我有帮助的是:

创建一个AnyShape

#if canImport(SwiftUI)

import SwiftUI

@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public struct AnyShape: Shape {
    public var make: (CGRect, inout Path) -> ()

    public init(_ make: @escaping (CGRect, inout Path) -> ()) {
        self.make = make
    }

    public init<S: Shape>(_ shape: S) {
        self.make = { rect, path in
            path = shape.path(in: rect)
        }
    }

    public func path(in rect: CGRect) -> Path {
        return Path { [make] in make(rect, &$0) }
    }
}

#endif

然后:

func createShape() -> AnyShape {
    switch self.card.shape {
    case .oval:
        return AnyShape(Capsule())
    case .rectangle:
        return AnyShape(Rectangle())
    case .circe:
        return AnyShape(Circle())
    }
}

推荐阅读