gpt4 book ai didi

swift - 在 SwiftUI 中动态获取 Shape 以供查看

转载 作者:行者123 更新时间:2023-12-03 09:28:51 24 4
gpt4 key购买 nike

使用 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)
}

关于swift - 在 SwiftUI 中动态获取 Shape 以供查看,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61503390/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com