使用 Swift 5.2 我想创建一个函数来动态更改Shape
我有一个像
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)
}
}
我想创建一个协议返回类型为 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()
}
}
我不能使用不透明类型some因为我返回不同的类型并且收到编译错误
Function declares an opaque return type, but the return statements in its body do not have matching underlying types
我也不能将其保留为协议类型,因为我收到错误
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)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)