Xcode 8 beta 6 AnyObject Swift 3 changes

4.2k Views Asked by At

Xcode beta 6 has changed some of the Swift Language

Since ‘id’ now imports as ‘Any’ rather than ‘AnyObject’, you may see errors where you were previously performing dynamic lookup on ‘AnyObject’.

I have tried the fix to either cast to AnyObject explicitly before doing the dynamic lookup, or force cast to a specific object type

But am not sure I am doing it correctly - can someone help please here is original working code from Beta 5

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! SpecialCell
        let maindata = values[(indexPath as NSIndexPath).row]
        cell.name.text = maindata["name"] as? String
        cell.id.text = maindata["id"] as? String
        //team_id.text = maindata["team_id"] as? String

        return cell
    }

https://www.dropbox.com/s/ln0vx3b9rbywv83/Screen%20Shot%202016-08-18%20at%2014.32.23.png?dl=0

2

There are 2 best solutions below

13
On BEST ANSWER

According to the beta 6 release notes you have to (bridge) cast to AnyObject

cell.name.text = (maindata["name"] as AnyObject) as? String

or force cast

cell.name.text = maindata["name"] as! String

That's one more reason to prefer custom classes / structs with distinct property types over common dictionaries.

1
On

I needed to make changes to my approach and ditch NSMutableArray (which I am pleased about)

so I declare the empty array as follows

var values = [[String:AnyObject]]()

and pop the data into it like so now

values = try! JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! [[String : AnyObject]];

one other minor tweak

let maindata = values[(indexPath).row]

Job done -thanks @vadian for jumping to chat to help me understand his answer which is technically correct