MK_ MK_ - 1 month ago 10x
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() {

var viewFrame = self.view.frame

viewFrame.origin.y += 20

viewFrame.size.height -= 20

logTableView.frame = viewFrame


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

logTableView.dataSource = self



override func viewDidAppear(animated: Bool) {


override func 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 =
return cell

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

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

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

fetchRequest.sortDescriptors = [sortDescriptor]

if let fetchResults = try managedObjectContext.executeFetchRequest(fetchRequest) as? [Event] {
eventItems = fetchResults


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.