[英]Value of protocol type '*' cannot conform to '*'; only struct/enum/class types can conform to protocols
I am facing the above error while trying this:我在尝试这个时遇到了上述错误:
protocol Style {}
struct StyleA: Style {}
struct StyleA: Style {}
struct StyleA: Style {}
struct Preset: Identifiable {
let id: UUID = UUID()
let title: String
let style: Style
}
extension View {
public func applyStyle<S>(_ style: S) where S : Style {
// USe the style here
}
}
// Initializg the data
static let mockedData: [Preset] = [
.init(title: "Title A", style: StyleA()),
.init(title: "Title A", style: StyleB()),
.init(title: "Title A", style: StyleC()),
]
// This line gives the error
myView.applyStyle(mockedData.first!.style)
How can I fix it?我该如何解决? Shouldn't it resolve the concrete type?
它不应该解决具体类型吗?
Thanks for your help.谢谢你的帮助。
You're running into the problem of protocols not conforming to themselves .您遇到了协议不符合自身的问题。 Your problem can be easily solved by making
applyStyle
non-generic, since Style
can be used as a concrete type.通过使
applyStyle
非泛型可以轻松解决您的问题,因为Style
可以用作具体类型。
extension View {
public func applyStyle(_ style: Style) {
// USe the style here
}
}
Since the Preset member style is Style, not any concrete type, you don't need the applyStyle to be generic, you can simply say:由于 Preset 成员样式是 Style,而不是任何具体类型,因此您不需要 applyStyle 是通用的,您可以简单地说:
public func applyStyle(_ style: Style)
try尝试
public protocol Style {}
struct StyleA: Style {}
struct StyleB: Style {}
struct StyleC: Style {}
struct Preset: Identifiable {
let id: UUID = UUID()
let title: String
let style: Style
}
extension View {
public func applyStyle(_ style: Style){
// USe the style here
}
}
// Initializg the data
let mockedData: [Preset] = [
.init(title: "Title A", style: StyleA()),
.init(title: "Title A", style: StyleB()),
.init(title: "Title A", style: StyleC()),
]
myView.applyStyle(mockedData.first!.style)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.