I'm getting this error when trying to pass values to text labels
Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value:
After readying SO threads about this I've tried the following and no luck:
photo
and the value was correct and not nil
username1Label.text = "test"
and same errorHere's a simplified version of the code:
class EventFeedCell: UITableViewCell {
@IBOutlet weak var username1Label: UILabel!
@IBOutlet weak var date1Label: UILabel!
@IBOutlet weak var photoId1Label: UILabel!
func setPhoto(_ photo:Photo) {
username1Label.text = photo.byUsername //I get the fatal error here
date1Label.text = photo.date
photoId1Label.text = photo.postId
}}
And the Photo
object
class Photo {
var postId = ""
var byId = ""
var byUsername = ""
var date = ""
var url = ""
var eventId = ""
}
cellForRowAt
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//Get a event feed photo cell
let cell = tableView.dequeueReusableCell(withIdentifier: EventFeedCell.eventFeedPhotoTableCell, for: indexPath) as! EventFeedCell
//Get the photo for this row
let photo = photos[indexPath.row]
//Set the details for the cell
cell.setPhoto(photo)
return cell
}
What else can I try? This is an exact copy of another TableView cell that does work (and for that reason I added a 1
in the label names just to be sure they are unique)
As soon as the cell is initilized your labels and other UI components might be nil so you have to set a value only if your UI components (Labels etc ) are initialized otherwise don't set. Simply add ?
before you access the text properties.
Here is a modified version of your setPhoto(:)
method.
func setPhoto(_ photo:Photo) {
username1Label?.text = photo.byUsername
date1Label?.text = photo.date
photoId1Label?.text = photo.postId
}
One thing to note is if your photoModel properties are optional you have to unwrap them first before you try to access. Below is another vresion of your setPhoto(:)
method only if your photoModel has optional properties.
func setPhoto(_ photo:Photo) {
// Optionally unwrap your photo properties.
gaurd let byUserName = photo.byUsername,
let date = photo.date,
let postId = photo.postId else {return}
// Safe to proceed if all your values are set in photoModel
username1Label?.text = byUserName
date1Label?.text = date
photoId1Label?.text = postId
}