Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

[AnyObject]?' does not have a member named 'subscript'

I'm loading a list of objects from a core data database into a table view.

class ScheduleViewController: UITableViewController {

    private var items: [AnyObject]?

    // MARK: - Table view data source
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let itemCount = items?.count {
            return itemCount
        }
    }

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

        if let act = items[indexPath.row] as Activity {
            if act.client != nil {
                // ...
            }
        }

        return cell
    }
}

The data is retrieved inside a closure so I have declared an items array as an optional because it might be nil in the first run.

I'm getting the error '[AnyObject]?' does not have a member named 'subscript' at this line if let act = items[indexPath.row] as? Activity.

I can't figure out how to resolve this.

like image 316
Isuru Avatar asked Sep 22 '14 13:09

Isuru


3 Answers

The array is declared as:

 private var items: [AnyObject]?

so, as you also said, it's an optional

In swift an optional is an enum, so a type on its own - and as an optional, it can contain either a nil value or an object of the contained type.

You want to apply the subscript to the array, not to the optional, so before using it you have to unwrap the array from the optional

items?[indexPath.row]

but that's not all - you also have to use the conditional downcast:

as? Activity

because the previous expression can evaluate to nil

So the correct way to write the if statement is

if let act = items?[indexPath.row] as? Activity {
like image 58
Antonio Avatar answered Nov 09 '22 19:11

Antonio


First of all you need to unwrap or optional chain the items as it can be nil. AnyObject has different behaviour when getting as element from array, due to the fact that AnyObject can be a function. You would have to cast from items like this:

if let act = items?[indexPath.row] as AnyObject? as Activity? {
    if act.client != nil {
        // ...
    }
}

If items will never contain a function you can use

private var items: [Any]?

instead and cast with:

if let act = items?[indexPath.row] as? Activity {
    if act.client != nil {
        // ...
    }
}
like image 25
Kirsteins Avatar answered Nov 09 '22 20:11

Kirsteins


I have fixed my problem by convert index var type from UInt to Int

let obj = items[Int(index)]

Hope this can help someone who still get this problem.

like image 1
z33 Avatar answered Nov 09 '22 20:11

z33