出现“致命错误:索引超出范围”:在swiftui

时间:2020-02-20 09:32:44

标签: list swiftui indices

已更新:错误:如果将if闭包(if!self.showMarkedOnly || name.marked {})放在list-foreach中,为什么类型'_'没有成员'1'?

代码版本4:

struct Name: Identifiable, Hashable {
    var id: String = UUID().uuidString
    var name: String
    var marked: Bool
    init(_ name: String, marked: Bool = false) { self.name = name; self.marked = marked }
}

struct TestView: View {
    @State private var list: [Name] = [Name("test1"), Name("test2"), Name("test3", marked: true), Name("test4"), Name("test5", marked: true), Name("test6"), Name("test7"), Name("test8")]
    @State private var showMarkedOnly = false

    var body: some View {
        VStack{
            Toggle(isOn: $showMarkedOnly) { Text("show marked only") }
            List {
                ForEach(Array(zip(0..., list)), id: \.1.id) { index, name in
//                    if !self.showMarkedOnly || name.marked {
                        HStack {
                            Text("\(index)").foregroundColor(name.marked ? .red : .gray)
                            Spacer()
                            Text("\(name.name)")
                        }
                        .background(Color.gray.opacity(0.001))
                        .onTapGesture {
                            self.list.remove(at: index)
                        }
//                    }
                }
            }
        }
    }
}

=========

已更新:我发现了代码版本2的问题,我必须提供ForEach的ID。并更新了代码版本2。

我发现了一种显示索引的优美方法,它避免了self.list [index]。但是我发现某些复杂代码中出现了“类型'_'没有成员'1'”错误。

代码版本3:

var body: some View {
        List {
            ForEach(Array(zip(0..., list)), id: \.1.id) { index, name in // a error occurs in some complex code: "Type '_' has no member '1'"
                HStack {
                    Text("\(index)")
                    Spacer()
                    Text("\(name.name)")
                }
                .background(Color.gray.opacity(0.001))
                .onTapGesture {
                    self.list.remove(at: index)
                }
            }
        }
    }

我显示一个列表,并删除我点击的项目。它是代码版本1,工作正常。 当我使用索引(代码版本2)将索引添加到列表项中时,点击后出现“致命错误:索引超出范围”。

代码版本1:

struct Name: Identifiable, Hashable {
    var id: String = UUID().uuidString
    var name: String
    init(_ name: String) { self.name = name }
}

struct TestView: View {
    @State private var list: [Name] = [Name("test1"), Name("test2"), Name("test3"), Name("test4"), Name("test5"), Name("test6"), Name("test7"), Name("test8")]

    var body: some View {
        List {
            ForEach(list) { name in
                HStack {
                    Text("\(0)")
                    Spacer()
                    Text("\(name.name)")
                }
                .background(Color.gray.opacity(0.001))
                .onTapGesture {
                    self.list = self.list.filter { $0 != name }
                }
            }
        }
    }
}

代码版本2:

struct TestView: View {
    @State private var list: [Name] = [Name("test1"), Name("test2"), Name("test3"), Name("test4"), Name("test5"), Name("test6"), Name("test7"), Name("test8")]

    var body: some View {
        List {
            //ForEach(list.indices) { index in
            ForEach(list.indices, id: \.self) { index in
                HStack {
                    Text("\(index)")
                    Spacer()
                    Text("\(self.list[index].name)")
                }
                .background(Color.gray.opacity(0.001))
                .onTapGesture {
                    self.list.remove(at: index)
                }
            }
        }
    }
}

3 个答案:

答案 0 :(得分:3)

@State是属性包装器,它将强制定义其中的View重新计算其主体。

对于您而言,如果您删除索引处的项目

HStack {
    Text("\(index)")
    Spacer()
    Text("\(self.list[index].name)")
}
.background(Color.gray.opacity(0.001))
.onTapGesture {
     self.list.remove(at: index)
 }

HStack中的文本

Text("\(self.list[index].name)")

崩溃,只是因为list [index]不再存在。

使用

ForEach(list.indices, id:\.self) { index in ... }

代替

ForEach(list.indices) { index in ... }

将强制SwiftUI重新创建TestView(请参阅ForEach构造函数中的id:\。self)

SwiftUI将使用@State属性包装器中包装的属性的新值来制作TestView的新副本。

更新

请不要更新您的问题...

您的最后一个代码版本4完全混乱,因此我将其重写为可以复制,粘贴和运行的内容

import SwiftUI

struct Name: Identifiable, Hashable {
    var id: String = UUID().uuidString
    var name: String
    var marked: Bool
    init(_ name: String, marked: Bool = false) { self.name = name; self.marked = marked }
}

struct ContentView: View {
    @State private var list: [Name] = [Name("test1"), Name("test2"), Name("test3", marked: true), Name("test4"), Name("test5", marked: true), Name("test6"), Name("test7"), Name("test8")]
    @State private var showMarkedOnly = false

    var body: some View {
        VStack{
            Toggle(isOn: $showMarkedOnly) {
                Text("show marked only")
            }.padding(.horizontal)
            List {
                ForEach(Array(zip(0..., list)).filter({!self.showMarkedOnly || $0.1.marked}), id: \.1.id) { index, name in
                    HStack {
                        Text("\(index)").foregroundColor(name.marked ? .red : .gray)
                        Spacer()
                        Text("\(name.name)")
                    }
                    .background(Color.gray.opacity(0.001))
                    .onTapGesture {
                        self.list.remove(at: index)
                    }
                }
            }
        }
    }
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

它看起来应该像enter image description here

基于讨论的更新

每个版本的构造函数使用内部不同的ViewBuilder功能

@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
extension ViewBuilder {

    /// Provides support for "if" statements in multi-statement closures, producing an `Optional` view
    /// that is visible only when the `if` condition evaluates `true`.
    public static func buildIf<Content>(_ content: Content?) -> Content? where Content : View

    /// Provides support for "if" statements in multi-statement closures, producing
    /// ConditionalContent for the "then" branch.
    public static func buildEither<TrueContent, FalseContent>(first: TrueContent) -> _ConditionalContent<TrueContent, FalseContent> where TrueContent : View, FalseContent : View

    /// Provides support for "if-else" statements in multi-statement closures, producing
    /// ConditionalContent for the "else" branch.
    public static func buildEither<TrueContent, FalseContent>(second: FalseContent) -> _ConditionalContent<TrueContent, FalseContent> where TrueContent : View, FalseContent : View
}

这是关于“实现细节”的,希望它将在下一版本中进行记录。 SwiftUI仍处于开发的早期阶段,我们必须小心。

让我们尝试迫使SwiftUI遵循我们自己的方式! 第一个单独的RowView

struct RowView: View {
    var showMarkedOnly: Bool
    var index: Int
    var name: Name
    //@ViewBuilder
    var body: some View {
        if !self.showMarkedOnly || name.marked {
            HStack {
                Text(verbatim: index.description).foregroundColor(name.marked ? .red : .gray)
                Spacer()
                Text(verbatim: name.name)
            }
            .background(Color.gray.opacity(0.001))

        }
    }
}

编译器抱怨

Function declares an opaque return type, but has no return statements in its body from which to infer an underlying type

取消注释以包裹身体的线

struct RowView: View {
    var showMarkedOnly: Bool
    var index: Int
    var name: Name
    @ViewBuilder
    var body: some View {
        if !self.showMarkedOnly || name.marked {
            HStack {
                Text(verbatim: index.description).foregroundColor(name.marked ? .red : .gray)
                Spacer()
                Text(verbatim: name.name)
            }
            .background(Color.gray.opacity(0.001))

        }
    }
}

现在我们可以按照您喜欢的方式使用代码了:-)

struct ContentView: View {
    @State private var list: [Name] = [Name("test1"), Name("test2"), Name("test3", marked: true), Name("test4"), Name("test5", marked: true), Name("test6"), Name("test7"), Name("test8")]
    @State private var showMarkedOnly = false

    var body: some View {
        VStack{
            Toggle(isOn: $showMarkedOnly) {
                Text("show marked only")
            }.padding(.horizontal)
            List {
                ForEach(Array(zip(0..., list)), id: \.1.id) { (index, name) in
                    RowView(showMarkedOnly: self.showMarkedOnly, index: index, name: name).onTapGesture {
                    self.list.remove(at: index)
                }
                }
            }
        }
    }
}

最终结果现在使用buildIf<Content>构造,并且所有代码都可以再次使用(结果看起来与上面显示的完全一样)

答案 1 :(得分:1)

这是因为indices不是您的状态,而是数组。因此,您更新了数组,但是@State实际上不够聪明,无法更新它包装的值的计算或下游属性。如果需要索引,请在ForEach中将标识符的来源设为

ForEach(0..<list.count, id: \.self) {
    // the rest should be ok here
}

答案 2 :(得分:0)

这是因为SwiftUI根据提供的原始数据重新加载其内容。 您可以通过修改

来解决
ForEach(list) { item in
    HStack {
        Text("\(item.id)")
        Spacer()
        Text("\(item.name)")
    }
    .onTapGesture {
        guard let itemIndex = self.list.firstIndex(of: item) else { return }
        self.list.remove(at:itemIndex)
    }
}

否则,您可以使用内置的.onDelete()方法(通过滑动项目来删除项目)来解决您的问题:

var body: some View {
    List {
        ForEach(list) { item in
            HStack {
                Text("\(item.id)")
                Spacer()
                Text("\(item.name)")
            }
            .background(Color.gray.opacity(0.001))
        }.onDelete(perform: delete)
    }
}

func delete(at offsets: IndexSet) {
    list.remove(atOffsets: offsets)
}