1
votes

Hello i have tableview and loading items when table numberOFRowsInSection 0 gives fatal error: unexpectedly found nil while unwrapping an Optional value

My code here

var itemsList = [String]()


internal func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
      self.itemsmessage.text = "Listed your last \(itemsList.count) items"

    return itemsList.count
}

Giving Error

fatal error: unexpectedly found nil while unwrapping an Optional value

When return nil gives this error in self.itemsmessage.text line. Thank you.

1
I think itemList array is not getting allocated when nubmerOfRowsInSection gets called.Ashish P.
@AshishP. so which code change i need ?SwiftDeveloper
is itemsList really an optional? if so, when in the flow of the app are you creating it?Eli Braginskiy
in viewDidLoad initialize itemList array...Ashish P.
Apart from the issue you should not put other code than the value to return in numberOfRowsInSection because the method could be called quite often even if the value does not change.vadian

1 Answers

2
votes

Your self.itemsmessage may not be connected to the actual control in your view controller. Check that its connected. To put safe code around that try this.

if let message = self.itemsmessage { message.text = "Listed your last \(itemsList.count) items" } else { print("Seems like your itemsmessage is not connected to a text label") }