Swift 在TableView中创建节时索引超出范围错误
我在使用JSON数据填充的ViewController中有TableView:Swift 在TableView中创建节时索引超出范围错误,swift,tableview,Swift,Tableview,我在使用JSON数据填充的ViewController中有TableView: var sections = [TabSection]() private func fetchJSON() { guard let url = URL(string: "https://example.com/example/example.php"), let value = name.addingPercentEncoding(withAllowedCharacters: .urlQu
var sections = [TabSection]()
private func fetchJSON() {
guard let url = URL(string: "https://example.com/example/example.php"),
let value = name.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)
else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = "name=\(value)".data(using: .utf8)
URLSession.shared.dataTask(with: request) { data, _, error in
guard let data = data else { return }
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let res = try decoder.decode([TabCollection].self, from: data)
let grouped = Dictionary(grouping: res, by: { $0.status })
let keys = grouped.keys.sorted()
self.sections = keys.map({TabSections(name: $0, collection: grouped[$0]!)})
DispatchQueue.main.async {
self.receiptTableView.reloadData()
}
}
catch {
print(error)
}
}.resume()
}
以下是JSON的结构,包括以下部分:
struct TabSections {
let name : String
let collection : [TabCollection]
}
struct TabCollection: Decodable {
let number, person, status: String
let maker: String
}
以下是TableView和选项卡如何填充JSON数据:
var sections = [TabSection]()
private func fetchJSON() {
guard let url = URL(string: "https://example.com/example/example.php"),
let value = name.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)
else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = "name=\(value)".data(using: .utf8)
URLSession.shared.dataTask(with: request) { data, _, error in
guard let data = data else { return }
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let res = try decoder.decode([TabCollection].self, from: data)
let grouped = Dictionary(grouping: res, by: { $0.status })
let keys = grouped.keys.sorted()
self.sections = keys.map({TabSections(name: $0, collection: grouped[$0]!)})
DispatchQueue.main.async {
self.receiptTableView.reloadData()
}
}
catch {
print(error)
}
}.resume()
}
该错误发生在numberofrowsinssection
下,并在定义节的第一行停止:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let section = sections[section]
return section.collection.count
}
我似乎无法理解为什么我在行
let section上接收到索引超出范围
,很可能您没有numberOfSections
方法,这意味着表视图默认为1节。由于数据模型最初可能没有元素,因此需要实现numberOfSections
以返回节中的元素数
override func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
您可以将该扩展用于Collection
fo安全地从集合中检索元素
extension Collection {
/// Returns the element at the specified index if it is within bounds, otherwise nil.
subscript (safe index: Index) -> Element? {
return indices.contains(index) ? self[index] : nil
}
}
因此,您的numberOfRowsInSection
将如下所示:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let section = sections[safe: section] else {
return 0
}
return section.collection.count
}
显示您的numberOfSections
方法。我感谢您的帮助,非常快速的附带问题,例如,如果JSON数据包含一些名为“已处理”和另一个名为“正在进行”的记录的状态,那么基于状态的部分是否可以改为表示“准备就绪”和“未准备就绪”呢?这是一个完全不同的问题。如果您无法找到解决方案,请关闭此问题并发布一个包含相关详细信息的新问题。但是是的,你可以根据需要改变它。