Fatal error: Index out of range when filling cells - swift

I am getting the this error: Index out of range when trying to fill cells out of a table, any idea why this happens?
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: VCInstanciasCell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! VCInstanciasCell
cell.siteLabel.text = String?([arrayItinerario[indexPath.section]][indexPath.row].ubicacion!) ?? ""
cell.txtLabel.text = String?([arrayItinerario[indexPath.section]][indexPath.row].maquinaTipo!) ?? ""
cell.orderLabel.text = String?([arrayItinerario[indexPath.section]][indexPath.row].fma!) ?? ""
cell.codeLabel.text = String?([arrayItinerario[indexPath.section]][indexPath.row].iso!) ?? ""
cell.newLabel.text = String?([arrayItinerario[indexPath.section]][indexPath.row].instanciaID!) ?? ""
cell.setLeftUtilityButtons(self.leftButtons(), withButtonWidth: 50.0)
return cell
}
the error is at cell.siteLabel.text = String?([arrayItinerario[indexPath.section]][indexPath.row].ubicacion!) ?? "" in indexPath.Row

It is quite hard to answer this question without seeing how arrayItinerario is defined, and what triggers the cellForRow (when is the timing you're calling reloadData)
But first of all, I'd try to simplify your code, it will make it easier to understand where the crash comes from, as you're using force unwrapped and also cannot know in which of the row/section you get the index out of range.
I added some checks + guards + prints, it will explain my answer + make your testing easier:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: VCInstanciasCell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! VCInstanciasCell
if let value = value(for: indexPath) {
cell.siteLabel.text = ""
if let ubicacion = value.ubicacion {
cell.siteLabel.text = String(ubicacion)
}
// and so on
} else {
print("couldn't get value for indexPath:\(indexPath)")
}
return cell
}
func value(for indexPath: IndexPath) -> SomeObject? {
let section = indexPath.section
let row = indexPath.row
guard section < arrayItinerario.count else {
print("section \(section) is out of range for list with count: \(arrayItinerario.count)")
return nil
}
let list = arrayItinerario[section]
guard row < list.count else {
print("row \(row) is out of range for list with count: \(list.count)")
return nil
}
return list[row]
}

Related

Swift Tableview reusable cell issue

I am having an issue with what I think is reusable cells in a tableview cell, unfortunately I can't work out how to force the state of the cell. I am fairly sure this is the issue because when I reload the tableview everything is displayed correctly. It's only when I scroll that I start to see issues, if I once again reload the display corrects itself.
This is the correct display :
and the incorrect display after scrolling about :
my cellForRowAt code :
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "historyGoalCell", for: indexPath)
let name = items[indexPath.section][indexPath.row].name
let date = dateManager.dateAsString(for: items[indexPath.section][indexPath.row].date!)
if tempDate != date {
// show header
cell.textLabel?.text = date
tempDate = date
} else {
// don't show header
cell.textLabel?.text = ""
}
cell.detailTextLabel?.text = "\(date),\(name ?? "")"
return cell
}
Thanks for any help, I have been stuck with this for a couple of days, very new to TableViews - thanks
tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
can be invoked in any order. It isn't called consistently from 1 to N, so logic with tempDate works not as planned. Better do some pre-work and make an array with indexes where you place headers. For example
struct Pair : Hashable {
var i : Int
var j : Int
}
//Somewhere one time before the first reloadData
var hasIndex : Set<Pair> = []
var tempDate: Date = Date.distantPast
for i in 0..<sections {
for j in 0..<rows[i] {
let name = items[i][j].name
let date = dateManager.dateAsString(for: items[i][j].date!)
if tempDate != date {
hasIndex.insert(Pair(i: i, j: j))
// OR items[i][j].showHeader = true
tempDate = date
} else {
// OR items[i][j].showHeader = false
}
}
}
...
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "historyGoalCell", for: indexPath)
let name = items[indexPath.section][indexPath.row].name
let date = dateManager.dateAsString(for: items[indexPath.section][indexPath.row].date!)
if hasIndex.contains(Pair(i: indexPath.section, j: indexPath.row)) {
// OR if items[indexPath.section][indexPath.row].showHeader {
cell.textLabel?.text = date
tempDate = date
} else {
cell.textLabel?.text = ""
}
cell.detailTextLabel?.text = "\(date),\(name ?? "")"
return cell
}

Hide cell from UITableView

I'm trying to hide cells from a UITableView. My codes are below.
When I open the app I see empty rows in my TableViewas you can see here
How can I hide or remove(not delete) empty cells from UITableView?
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! FeedTableViewCell
let row = self.items[indexPath.row]
cell.lblTitle.text = row.title
cell.isHidden = !checkCurrentUser(email: row.email)
return cell
}
I added filtered array but then I take different error like this. My new codes are below. How can I solve this problem?
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! FeedTableViewCell
let row = self.items[indexPath.row]
self.items = self.items.filter{checkCurrentUser(email: $0.email)}
cell.lblTitle.text = row.title
//cell.isHidden = !checkCurrentUser(email: row.email)
return cell
}
Whole codes are below
import UIKit
import Firebase
class OyuncularVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
var items = [ItemModel]()
#IBOutlet weak var tblView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tblView.tableFooterView = UITableViewHeaderFooterView()
retrieveItems()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! FeedTableViewCell
let row = self.items[indexPath.row]
self.items = self.items.filter{checkCurrentUser(email: $0.email)} //bunu ekledim siliceksem bunu silicem aga
cell.lblTitle.text = row.title
//cell.isHidden = !checkCurrentUser(email: row.email)
return cell
}
/* Retriev Items */
func retrieveItems() {
DataService.dataService.ITEM_REF.observe(.value, with: { (snapshot: DataSnapshot?) in
if let snapshots = snapshot?.children.allObjects as? [DataSnapshot] {
self.items.removeAll()
print(snapshots.count)
for snap in snapshots {
if let postDic = snap.value as? Dictionary<String, AnyObject> {
let itemModel = ItemModel(key: snap.key, dictionary: postDic)
print(itemModel)
self.items.insert(itemModel, at: 0)
}
}
self.tblView.reloadData()
}
})
}
func checkCurrentUser(email: String) -> Bool {
let currentUser = Auth.auth().currentUser
return email == currentUser?.email
}
}
}
If you want to display only the emails of the current user what don't you filter the items in the database (applying a predicate) which is the most efficient way.
Or filter the items in the for snap in snapshots loop.
However if you want to keep the entire data set declare a second array
var items = [ItemModel]()
var filteredItems = [ItemModel]()
and replace
for snap in snapshots {
if let postDic = snap.value as? Dictionary<String, AnyObject> {
let itemModel = ItemModel(key: snap.key, dictionary: postDic)
print(itemModel)
self.items.insert(itemModel, at: 0)
}
}
with the following it performs the check in the loop
let currentUser = Auth.auth().currentUser
self.filteredItems.removeAll()
for snap in snapshots {
if let postDic = snap.value as? Dictionary<String, AnyObject> {
let itemModel = ItemModel(key: snap.key, dictionary: postDic)
print(itemModel)
self.items.insert(itemModel, at: 0)
if itemModel.email == currentUser?.email {
self.filteredItems.insert(itemModel, at: 0)
}
}
}
And replace also the two data source methods with
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! FeedTableViewCell
let row = self.filteredItems[indexPath.row]
cell.lblTitle.text = row.title
return cell
}
And delete the method checkCurrentUser

Thread 1: Fatal error: Index out of range, return array.count + 1

I have a tableview with at all times one cell. If there is data to download from Firebase it will put it in an array called posts. When there's for example, two "in my case" servers that the user will download, it will only display one cell instead of two. I thought I could fix this by changing return posts.count to return posts.count + 1 because of the one cell that will be shown at all times. But if I use return posts.count + 1 I will get a
Thread 1: Fatal error: Index out of range
error on line let post = posts[indexPath.row]. I have read about this error, but I can't seem to fix it.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if posts.count == 0 {
self.tableView.setEmptyMessage("No Servers uploaded!")
return 1
} else {
self.tableView.restore()
return posts.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "ProfileCell", for: indexPath) as! ProfileCellTableViewCell
cell.delegate = self
return cell
}else {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCellMYposts
cell.Map_image.image = nil
let post = posts[indexPath.row]
cell.post = post
cell.delegate = self
return cell
}
}
Assuming you have some piece of data in posts[0], you are never actually displaying it. For indexPath.row = 0, you are displaying a profile cell, and then you start displaying the data from posts[1] and on. Change your problem line to:
let post = posts[indexPath.row - 1]

Displaying two reusable cells in tableview - Swift 3

I have two custom reusable table view cells in my table view. The first cell, I would like it to be present at all times. The second cell and beyond, are returning a count that is being passed from mysql database.
// return the amount of cell numbers
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
// cell config
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row < 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! InfoCell
//set the data here
return cell
} else {
let Postcell = tableView.dequeueReusableCell(withIdentifier: "PostCell", for: indexPath) as! PostCell
let post = posts[indexPath.row]
let image = images[indexPath.row]
let username = post["user_username"] as? String
let text = post["post_text"] as? String
// assigning shortcuts to ui obj
Postcell.usernameLbl.text = username
Postcell.textLbl.text = text
Postcell.pictureImg.image = image
return Postcell
}
} // end of function
My first cell is there and so are the post.count, but for some reason the posts.count is missing one post and I believe this is because of the first cell. Can anybody help me with this? thanks in advance.
You need to adjust the value returned from numberOfRowsInSection to account for the extra row. And you would need to adjust the index used to access values from your posts array to deal with the extra row.
But a much better solution is to use two sections. The first section should be your extra row and the second section would be your posts.
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 1
} else {
return posts.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! InfoCell
//set the data here
return cell
} else {
let Postcell = tableView.dequeueReusableCell(withIdentifier: "PostCell", for: indexPath) as! PostCell
let post = posts[indexPath.row]
let image = images[indexPath.row]
let username = post["user_username"] as? String
let text = post["post_text"] as? String
// assigning shortcuts to ui obj
Postcell.usernameLbl.text = username
Postcell.textLbl.text = text
Postcell.pictureImg.image = image
return Postcell
}
}

Cannot invoke initializer for type 'Double' with an argument list of type '([Int])'

I'm converting the timestamp to normal type but I'm getting this error --- Cannot invoke initializer for type 'Double' with an argument list of type '([Int])', How to fix it?
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "jobCell", for: indexPath)
//print jobTime = 1504753200
let unixTimestamp = Double(jobTime) //error here
let date = Date(timeIntervalSince1970: unixTimestamp)
cell.textLabel?.text = "\(jobTime[indexPath.row])-\(jobEndTime[indexPath.row])"
return cell
}
I'm retrieving the JSON data and put into table view cell
var jobTime = [Int]()
var jobEndTime = [Int]()
viewDidLoad
guard let jobs = json["jobs"] as? [[String:Any]] else {return }
for job in jobs {
if let id = job["jobTime"] as? Int{
self.jobTime.append(id)
}
if let id = job["jobEndTime"] as? Int{
elf.jobEndTime.append(id)
}
}
self.tableView.reloadData()
}
Try this-
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "jobCell", for: indexPath)
//print jobTime = 1504753200
let unixTimestamp = Double(jobTime[indexPath.row]) //Change here
let date = Date(timeIntervalSince1970: unixTimestamp)
cell.textLabel?.text = "\(jobTime[indexPath.row])-\(jobEndTime[indexPath.row])"
return cell
}