问题描述
Swift/ContiguousArrayBuffer.swift:580:致命错误:索引超出范围 2021-05-07 09:59:38.171277+0200 Section [4462:220358] Swift/ContiguousArrayBuffer.swift:580:致命错误:索引超出范围
我一直在寻找解决方案,但我发现的所有解决方案似乎都不适用于我的代码。
FIY 这是我在 SwiftUI 或 Swift 中的第一个应用程序,所以我对此完全陌生。
所以如果有人能帮我解释一下我需要改变什么以及为什么我会非常感激:)
这里有一些代码,我希望能帮助你找到问题的根源。
我的模型:
//
// Item.swift
// Section
//
// Created by Niklas Peterson on 2021-03-11.
//
import Foundation
struct Item: Identifiable,Hashable,Codable {
var id = UUID().uuidString
var name: String
}
extension Item {
static func getAll() -> [Item] {
let key = UserDefaults.Keys.items.rawValue
guard let items: [Item] = UserDefaults.appGroup.getArray(forKey: key) else {
let items: [Item] = [.section1]
UserDefaults.appGroup.setArray(items,forKey: key)
return items
}
return items
}
static let section1: Item = {
return Item(name: "Section")
}()
}
extension Item {
static func fromId(_ id: String) -> Item? {
getAll().first { $0.id == id }
}
}
//
// UserDefaults+Ext.swift
// Section
//
// Created by Niklas Peterson on 2021-03-11.
//
import Foundation
extension UserDefaults {
static let appGroup = UserDefaults(suiteName: "************ hidden ;) ")!
}
extension UserDefaults {
enum Keys: String {
case items
}
}
extension UserDefaults {
func setArray<Element>(_ array: [Element],forKey key: String) where Element: encodable {
let data = try? JSONEncoder().encode(array)
set(data,forKey: key)
}
func getArray<Element>(forKey key: String) -> [Element]? where Element: Decodable {
guard let data = data(forKey: key) else { return nil }
return try? JSONDecoder().decode([Element].self,from: data)
}
}
内容视图:
//
// ContentView.swift
// Section
//
// Created by Niklas Peterson on 2021-03-11.
//
import SwiftUI
struct ContentView: View {
@State private var items = Item.getAll()
func saveItems() {
let key = UserDefaults.Keys.items.rawValue
UserDefaults.appGroup.setArray(items,forKey: key)
}
func move(from source: IndexSet,to destination: Int) {
items.move(fromOffsets: source,toOffset: destination)
saveItems()
}
func delete(at offsets: IndexSet) {
items.remove(atOffsets: offsets)
saveItems()
}
var body: some View {
NavigationView {
List {
ForEach(items.indices,id: \.self) { index in
TextField("",text: $items[index].name,onCommit: {
saveItems()
})
}
.onDelete(perform: delete)
.onMove(perform: move)
}
.toolbar {
ToolbarItemGroup(placement: .primaryAction) {
HStack {
Button(action: {
self.items.insert(Item(name: ""),at: 0)
}) {
Image(systemName: "plus.circle.fill")
}
EditButton()
}
}
}
.navigationBarTitle("Sections")
.listStyle(InsetGroupedListStyle())
}
}
}
解决方法
注意:这在 iOS15
中不再是问题,因为 List
现在支持 binding
这显然是 SwiftUI
本身的一个错误。
经过研究,发现问题出在TextField
绑定上。如果您用简单的 TextField
视图替换 Text
,一切都会正常工作。看起来在删除项目后,TextField
绑定正在尝试访问 deleted
项目,但找不到它导致崩溃。
这篇文章帮助我解决了这个问题,请查看 SwiftbySundell
因此,为了解决这个问题,我们将不得不更深入地研究 Swift 的集合 API,以使我们的数组索引真正独一无二。
- 引入一个自定义集合,它将另一个集合的索引与其包含的元素的标识符相结合。
struct IdentifiableIndices<Base: RandomAccessCollection>
where Base.Element: Identifiable {
typealias Index = Base.Index
struct Element: Identifiable {
let id: Base.Element.ID
let rawValue: Index
}
fileprivate var base: Base
}
- 使我们的新集合符合标准库的
RandomAccessCollection
协议,
extension IdentifiableIndices: RandomAccessCollection {
var startIndex: Index { base.startIndex }
var endIndex: Index { base.endIndex }
subscript(position: Index) -> Element {
Element(id: base[position].id,rawValue: position)
}
func index(before index: Index) -> Index {
base.index(before: index)
}
func index(after index: Index) -> Index {
base.index(after: index)
}
}
- 通过将以下计算属性添加到所有兼容的基本集合(即支持随机访问并且还包含
IdentifiableIndices
元素的集合),可以轻松创建Identifiable
实例:
extension RandomAccessCollection where Element: Identifiable {
var identifiableIndices: IdentifiableIndices<Self> {
IdentifiableIndices(base: self)
}
}
- 最后,让我们还使用方便的 API 扩展 SwiftUI 的
ForEach
类型,让我们可以迭代IdentifiableIndices
集合,而无需手动访问每个索引的rawValue
:
extension ForEach where ID == Data.Element.ID,Data.Element: Identifiable,Content: View {
init<T>(
_ data: Binding<T>,@ViewBuilder content: @escaping (T.Index,Binding<T.Element>) -> Content
) where Data == IdentifiableIndices<T>,T: MutableCollection {
self.init(data.wrappedValue.identifiableIndices) { index in
content(
index.rawValue,Binding(
get: { data.wrappedValue[index.rawValue] },set: { data.wrappedValue[index.rawValue] = $0 }
)
)
}
}
}
- 最后,在您的
ContentView
中,您可以将ForEach
更改为:
ForEach($items) { index,item in
TextField("",text: item.name,onCommit: {
saveItems()
})
}
@Binding
属性包装器让我们可以声明一个值实际上来自其他地方,并且应该在两个地方共享。在我们的列表中删除 Item
时,数组 items
变化很快,根据我的经验,这会导致问题。
SwiftUI
似乎对它创建的集合绑定应用了某种形式的缓存,这可能会导致在下标到我们的底层 Item
数组时使用过时的索引 - 这会导致应用程序崩溃越界错误。