英文:
if else "Type '()' cannot conform to 'View'" error
问题
以下是您要翻译的内容:
以下代码生成了“类型'()'无法符合'View'”错误,但为什么?
var body: some View {
VStack {
if isLineGraph == true {
chartAverage() <- 类型'()'无法符合'View'
} else {
chartActual()
}
}
}
如果我将chartAverage()
更改为chartActual()
,则会收到相同的错误。不理解为什么会出现错误,如果出现错误,为什么不针对两个函数都生成错误?
chartAverage()
的示例:
func chartAverage() {
@Environment(\.colorScheme) var scheme
var cloudCoverArray: [CloudCoverArray] = GlobalVariables.masterCloudCover
Chart {
ForEach(cloudCoverArray, id:\.self) {item in
LineMark(
x: .value("Date", item.date),
y: .value("CloudCover", item.averageCloud),
series: .value("Date", "CloudCover")
)
.foregroundStyle(Color.gray)
.lineStyle(StrokeStyle(lineWidth: 2))
}
}
.padding()
.frame(width: GlobalVariables.screenWidth - 32, height: 340 + 30) // 30 = top + bottom padding from CalculateView
.clipShape(RoundedRectangle(cornerRadius: 15))
//.padding()
.background {
RoundedRectangle(cornerRadius: 10, style: .continuous)
.fill((scheme == .dark ? Color.black : Color.white).shadow(.drop(radius: 2)))
}
}
英文:
The following code generates the "Type '()' cannot conform to 'View'" error, but why?
var body: some View {
VStack{
if isLineGraph == true {
chartAverage() <- Type '()' cannot conform to 'View'
} else {
chartActual()
}
If I change chartAverage() to chartActual() you get the same error. Don't understand why I am getting the error and if I am why it doesn't generate them against both functions?
Example of chartAverage()
func chartAverage() {
@Environment(\.colorScheme) var scheme
var cloudCoverArray: [CloudCoverArray] = GlobalVariables.masterCloudCover
Chart {
ForEach(cloudCoverArray, id:\.self) {item in
LineMark(
x: .value("Date", item.date),
y: .value("CloudCover", item.averageCloud),
series: .value("Date", "CloudCover")
)
.foregroundStyle(Color.gray)
.lineStyle(StrokeStyle(lineWidth: 2))
}
}
.padding()
.frame(width: GlobalVariables.screenWidth - 32, height: 340 + 30) // 30 = top + bottom padding from CalculateView
.clipShape(RoundedRectangle(cornerRadius: 15))
//.padding()
.background {
RoundedRectangle(cornerRadius: 10, style: .continuous)
.fill((scheme == .dark ? Color.black : Color.white).shadow(.drop(radius: 2)))
}
}
答案1
得分: 1
chartAverage()
和 chartActual()
必须都返回 View
类型,通常是 some View
。如果没有这样做,视图构建器会在遇到第一个错误时失败,并且你不会得到第二个错误的报错信息。
你现在有这样的代码:
func chartAverage() {
你需要这样:
func chartAverage() -> some View {
英文:
chartAverage()
and chartActual()
must both return View
types, typically some View
. Without this, the view builder fails at the first error it encounters, and you don't get an error for the second mistake.
You have this:
func chartAverage() {
You need this:
func chartAverage() -> some View {
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论