MK_ MK_ - 3 months ago 15
Swift Question

CoreData/TableView - Ambiguous use of 'subscript'

When I try to create a TableView with CoreData data I get this error and don't know how to fix it. I saved the CoreData in another class. I don't know if I even created the TableView right.

class listEvents: UITableViewController {

var logTableView = UITableView(frame: CGRectZero, style: .Plain)
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
var eventItems: AnyObject?

override func viewDidLoad() {
super.viewDidLoad()

var viewFrame = self.view.frame

viewFrame.origin.y += 20

viewFrame.size.height -= 20


logTableView.frame = viewFrame

self.view.addSubview(logTableView)

logTableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: "EventCell")


logTableView.dataSource = self

fetchLog()

}

override func viewDidAppear(animated: Bool) {


}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()

}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return eventItems!.count

}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("EventCell") as! UITableViewCell!

let eventItem = eventItems! [indexPath.row] <-- Error here

cell.textLabel?.text = eventItem.name
return cell
}

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let eventItem = eventItems! [indexPath.row] <-- Error here
print(eventItem.id)
}


func fetchLog() {
let fetchRequest = NSFetchRequest(entityName: "Event")


let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)


fetchRequest.sortDescriptors = [sortDescriptor]

do{
if let fetchResults = try managedObjectContext.executeFetchRequest(fetchRequest) as? [Event] {
eventItems = fetchResults
}
}catch{
print("ERROR")
}
}
}

Answer

You have this declaration:

var eventItems: AnyObject?

Then later on you do this:

let eventItem = eventItems! [indexPath.row] 

The problem is that you declared eventItems as AnyObject?, and AnyObject does not accept subscripts. It can literally be any object at all, and not every class works with subscripts, so Swift doesn't know what to do.

Since you're assigning eventItems as the result of a fetch request, it should be declared as either an NSArray? or as something like [Event]?. Also, using that ! after eventItems puts you at serious risk of a crash; don't ever use ! unless you're absolutely sure that you won't accidentally have a nil value.

Comments