我将数据传递给 ForEach,在使用该.enumerated()方法之前没有出现任何问题。我收到的错误是:
通用结构“ForEach”要求“EnumeratedSequence<[String]>”符合“RandomAccessCollection”
类型“EnumeratedSequence<[String]>.Element”(又名“(offset: Int, element: String)”)不能符合“Hashable”;只有 struct/enum/class 类型可以符合协议
至于第一个错误,您将在代码中看到我只是传递了一个数组。所以我不明白这个错误。
至于第二个错误我不确定。
传递到数组中的数据是从 UserDefaults 提供的,如下面的代码所示。
import SwiftUI
struct ContentView: View {
@State private var name = ""
@State private var myArray = [String]()
@State private var isShowing = false
@State private var actionSheet = false
let defaults = UserDefaults.standard
var body: some View {
VStack {
Spacer()
TextField("Insert name", text: $name)
.padding()
ScrollView(.horizontal) {
HStack {
ForEach(myArray.enumerated(), id: \.self) { index, name in
Circle()
.onTapGesture {
self.actionSheet.toggle()
}
.frame(width: 50, height: 50)
.actionSheet(isPresented: $actionSheet) {
ActionSheet(title: Text("Titles"), message: Text("This is the message"), buttons: [
.default(Text("Delete item")){
var loaded = defaults.stringArray(forKey: "myData")
}
])
}
}
}.padding()
}
Text(String(myArray.count))
.font(.system(size: 30, weight: .black, design: .rounded))
.foregroundColor(.green)
VStack {
Button(action: {self.isShowing.toggle() }){ Text("Show")}
if isShowing {
ForEach(myArray, id: \.self) { name in
Text(name)
}
}
}.animation(.interactiveSpring())
Spacer()
HStack {
Button(action: {
}){
Text("Delete")
.fontWeight(.bold)
.padding()
.foregroundColor(.white)
.background(Color.red)
.cornerRadius(10)
}
Button(action: {
myArray.append(name)
defaults.set(myArray, forKey: "myData")
self.name = ""
}){
Text("Save")
.fontWeight(.bold)
.padding()
.foregroundColor(.white)
.background(Color.blue)
.cornerRadius(10)
}
}
}.onAppear {
guard let loaded = defaults.object(forKey: "myData") as? [String] else {
return
}
self.myArray = loaded
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Run Code Online (Sandbox Code Playgroud)

New*_*Dev 15
ForEach期望一个符合 的类型RandomAccessCollection,但Array.enumerated()返回一个EnumeratedSequence<[Element]>仅符合 的Sequence。
您可以将其包装在 an 中Array以获得一个数组,该数组符合RandomAccessCollection:
ForEach(Array(myArray.enumerated()), id: \.1) { (n, element) in
}
Run Code Online (Sandbox Code Playgroud)
我个人喜欢用zip
ForEach(zip(myArray.indices, myArray), id: \.1) { (index, element) in
}
Run Code Online (Sandbox Code Playgroud)
因为它也适用于非整数索引。
Asp*_*eri 13
返回enumerated()元组序列,您可以将其转换为数组,例如
HStack {
ForEach(Array(myArray.enumerated()), id: \.1) { index, name in
Circle()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5626 次 |
| 最近记录: |