使用Swift 5.2,我想创建一个函数来动态更改形状
我有一个像
import SwiftUI
struct CardView: View {
let suit : Suite
let rank : Rank
var body: some View {
getShape(suite: .heart)
.fill(Color.red) // .fill(suit.color)
.frame(width: 100, height: 100)
}
}
我想创建一个协议(protocol)返回类型为Shape的函数,在下面的示例中,我将自定义形状替换为通用
func getShape(suite:Suite) -> Shape {
switch suite {
case .heart:
return Circle() // Heart()
case .diamond:
return Rectangle() // Diamond()
case .spade:
return Circle() // Heart()
case .club:
return Circle() // Club()
}
}
我不能与某些对象一起使用不透明类型,因为我返回的是不同类型,并且出现编译错误
Function declares an opaque return type, but the return statements in its body do not have matching underlying types
也无法将其保留为协议(protocol)类型,因为出现错误
Protocol 'Shape' can only be used as a generic constraint because it has Self or associated type requirements
有什么方法可以优雅地实现这一目标吗?
最佳答案
通过将@Asperi的答案与
struct AnyShape: Shape {
init<S: Shape>(_ wrapped: S) {
_path = { rect in
let path = wrapped.path(in: rect)
return path
}
}
func path(in rect: CGRect) -> Path {
return _path(rect)
}
private let _path: (CGRect) -> Path
}
我可以将其更改为
func getShape(suite:Suite) -> some Shape {
switch suite {
case .club:
return AnyShape(Club())
case .diamond:
return AnyShape(Diamond())
case .heart:
return AnyShape(Heart())
case .spade:
return AnyShape(Spade())
}
}
struct CardView: View {
let suit : Suite
let rank : Rank
var body: some View {
getShape(suite: suit)
.fill(Color.red)
.frame(width: 100, height: 100)
}