Luis Delgado Luis Delgado - 7 months ago 94
Swift Question

How to pass a Struct to a method that is expecting an AnyObject?

I am starting to get my head around Structs in Swift, and changed one of our app's data models to a Struct.

In a view controller we have, we use this method:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//Some code
self.performSegueWithIdentifier("JobDetailSegue", sender: job)
}


job
above is of type
JobModel
, which is a class that I just converted to a struct.

However, compilation is failing on the line with
self.performSegueWithIdentifier("JobDetailSegue", sender: job)
with error
Cannot convert value of type 'JobModel?' to expected argument type 'AnyObject?'


So I take it that methods that accept an
AnyObject?
won't take a Struct as an argument? If so, what is the correct way to use Structs in this scenario (if at all)?

Answer

I think maybe you can still use your Struct, but add a variable to it that returns a dictionary format of everything that's in your struct, which inherits from NSObject as @dasdom was saying. So you could do something like this:

struct JobModel {
    var someData: String!
    var someMoreData: AnyObject!
    //all of your other struct members, and then a last one which returns a dict
    var jobsDict [String: AnyObject] {
        return ["someKey": someData, "anotherKey": someMoreData]
    }
}

Then, when you perform your segue, instead of passing the whole job object, you can just do: self.performSegueWithIdentifier("identifier", sender: job.jobsDict)

Comments