gpt4 book ai didi

foreach - Array.forEach 创建错误 "Cannot convert value of type ' ( )' to closure result type ' _'"

转载 作者:行者123 更新时间:2023-12-03 21:18:52 28 4
gpt4 key购买 nike

我正在尝试遍历 SwuftUI 中的数组以在不同位置呈现多个文本字符串。手动遍历数组是可行的,但使用 forEach-loop 会产生错误。
在下面的代码示例中,我已经注释掉了手动方法(有效)。
这种方法在本教程中用于绘制线条 ( https://developer.apple.com/tutorials/swiftui/drawing-paths-and-shapes )

(作为一个额外的问题:有没有办法通过这种方法获取各个位置的索引/键,而无需将该键添加到每一行的位置数组中?)

我已经尝试了各种方法,比如 ForEach,在那里添加了 identify(),并为闭包添加了各种类型定义,但我最终还是创建了其他错误

import SwiftUI

var positions: [CGPoint] = [
CGPoint(x: 100, y: 100),
CGPoint(x: 100, y: 200),
CGPoint(x: 100, y: 300),
]

struct ContentView : View {
var body: some View {
ZStack {
positions.forEach { (position) in
Text("Hello World")
.position(position)
}
/* The above approach produces error, this commented version works
Text("Hello World")
.position(positions[0])
Text("Hello World")
.position(positions[1])
Text("Hello World")
.position(positions[2]) */
}
}
}

#if DEBUG
struct ContentView_Previews : PreviewProvider {
static var previews: some View {
ContentView()
}
}
#endif

最佳答案

并非所有内容都在 View 正文中有效。如果要执行 for-each 循环,则需要使用特殊 View ForEach :

https://developer.apple.com/documentation/swiftui/foreach

View 需要一个可识别数组,可识别数组要求元素符合Hashable。您的示例需要像这样重写:

import SwiftUI

extension CGPoint: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(x)
hasher.combine(y)
}
}
var positions: [CGPoint] = [
CGPoint(x: 100, y: 100),
CGPoint(x: 100, y: 200),
CGPoint(x: 100, y: 300),
]

struct ContentView : View {
var body: some View {
ZStack {
ForEach(positions.identified(by: \.self)) { position in
Text("Hello World")
.position(position)
}
}
}
}

或者,如果您的数组无法识别,您可以使用它:

var positions: [CGPoint] = [
CGPoint(x: 100, y: 100),
CGPoint(x: 100, y: 200),
CGPoint(x: 100, y: 300),
]

struct ContentView : View {
var body: some View {
ZStack {
ForEach(0..<positions.count) { i in
Text("Hello World")
.position(positions[i])
}
}
}
}

关于foreach - Array.forEach 创建错误 "Cannot convert value of type ' ( )' to closure result type ' _'",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56916079/

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