Viene visualizzato un messaggio di errore "Rilevato inaspettatamente nil
durante lo scucamento di uno Optional
" da Swift, con la classe di seguito. L'errore si verifica sulla linea:Trovato inaspettatamente nil durante lo srotolamento di un valore facoltativo swift
(cell.contentView.viewWithTag(1) as UILabel).text = object["firstName"] as? String
Ho una classe cella personalizzato con 2 UILabels etichettato 1 e 2, le uscite sono impostate
import UIKit
import Foundation
class dictionaryTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
var objects = NSMutableArray()
var dataArray = [["firstName":"Debasis","lastName":"Das","email":"[email protected]"],["firstName":"John","lastName":"Doe","email":"[email protected]"],["firstName":"Jane","lastName":"Doe","email":"[email protected]"],["firstName":"Mary","lastName":"Jane","email":"[email protected]"]]
@IBOutlet
var tableView: UITableView!
var items: [String] = ["We", "Heart", "Swift"]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count;//self.items.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
//cell.textLabel?.text = self.items[indexPath.row]
//return cell
let cell = tableView.dequeueReusableCellWithIdentifier("MyCell", forIndexPath: indexPath) as UITableViewCell
let object = dataArray[indexPath.row] as NSDictionary
(cell.contentView.viewWithTag(1) as UILabel).text = object["firstName"] as? String
(cell.contentView.viewWithTag(2) as UILabel).text = object["lastName"] as? String
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
println("You selected cell #\(indexPath.row)!")
}
}
Credo che il problema è con 'viewWithTag (_ :)', che restituisce un '' UIView (opzionale 'UIView')?. Se è 'nil', l'accesso alla proprietà' text' provoca l'arresto anomalo. Prova a cambiare il codice in 'se lasci tag1 = cell.contentView.viewWithTag (1) come UILabel {...}' e mettici un breakpoint per vedere cosa succede. – Romain