Luis Delgado Luis Delgado - 2 years ago 161
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)

above is of type
, 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
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 Source

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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download