Per Eriksson
Per Eriksson

Reputation: 534

Cannot pass array into performSegueWithIdentifier

I want to pass an array named products of type [Product] through performSegueWithIdentifier(self.segueName, sender: products)

I want to receive the array in the sender parameter of prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)

However, this does not compile: Cannot convert value of type '[Product]' to expected argument type 'AnyObject?'

Why do I want to do this? Simply because I want to avoid adding a global variable in my Controller class for this purpose.

How can I achieve this?

I have tried to convert the array to AnyObject beforehand. This solution compiles but the resulting value in the sender parameter in the prapareForSegue function contains nil.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == segueName {
        let productsController = segue.destinationViewController as! ProductsController
        productsController.products = sender as! [Product]
    }
}

override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    let company = DataService.allCompanies[indexPath.item]
    DataService.getAllProductsForCompanies([company]) { (products: [Product]) -> () in
        dispatch_async(dispatch_get_main_queue()) {
            print("getAllProductsForCompanies for companyId: \(company.companyId)")
            self.performSegueWithIdentifier(self.segueName, sender: products as? AnyObject)
        }
    }
}

Upvotes: 0

Views: 714

Answers (2)

Per Eriksson
Per Eriksson

Reputation: 534

The real problem was that I had declared my Product entity as a struct and not a class. This prevented the array to be handled as an AnyObject.

Using a class allowed me to pass [Product] into performSegueWithIdentifier without any type casting and the received parameter was successfully cast back again using sender as! [Product]

Upvotes: 0

adamsuskin
adamsuskin

Reputation: 547

Directly from the Swift Programming Language reference:

The as? version of the downcast operator returns an optional value of the protocol’s type, and this value is nil if the instance does not conform to that protocol.

So if the value you are getting is nil, it means [Product] does not conform to AnyObject? protocol which is expected since [Product] is an array (see here: Structures as AnyObject).

What you can do is typecast [Product] to NSArray, since that is an object that conforms to AnyObject?.

self.performSegueWithIdentifier(self.segueName, sender: (products as NSArray) as? AnyObject)

Look here for more: AnyObject to Array.

Let me know how it goes! Good luck!

Upvotes: 2

Related Questions