Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 无法将数组传递到performsguewithidentifier_Ios_Arrays_Swift2 - Fatal编程技术网

Ios 无法将数组传递到performsguewithidentifier

Ios 无法将数组传递到performsguewithidentifier,ios,arrays,swift2,Ios,Arrays,Swift2,我想通过performsguewithidentifier(self.segueName,sender:products) 我想在prepareforsgue(segue:UIStoryboardSegue,sender:AnyObject?)的sender参数中接收数组 但是,这不会编译:无法将“[Product]”类型的值转换为预期的参数类型“AnyObject?” 我为什么要这样做?这仅仅是因为我希望避免为此在控制器类中添加全局变量 我怎样才能做到这一点 我已经尝试将数组事先转换为AnyO

我想通过
performsguewithidentifier(self.segueName,sender:products)

我想在
prepareforsgue(segue:UIStoryboardSegue,sender:AnyObject?)的
sender
参数中接收数组

但是,这不会编译:
无法将“[Product]”类型的值转换为预期的参数类型“AnyObject?”

我为什么要这样做?这仅仅是因为我希望避免为此在控制器类中添加全局变量

我怎样才能做到这一点

我已经尝试将数组事先转换为
AnyObject
。此解决方案进行编译,但
prapareForSegue
函数中
sender
参数中的结果值包含
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)
        }
    }
}

直接从Swift编程语言参考:

as?downcast运算符的版本返回协议类型的可选值,如果实例不符合该协议,则该值为nil

因此,如果您得到的值为零,则表示
[Product]
不符合
AnyObject?
协议,因为
[Product]
是一个数组(请参见此处:)

您可以做的是将
[Product]
类型转换到NSArray,因为这是一个符合AnyObject?的对象

self.performSegueWithIdentifier(self.segueName, sender: (products as NSArray) as? AnyObject)
请在此处查看更多:


让我知道进展如何!祝你好运

真正的问题是,我将我的产品实体声明为一个结构,而不是一个类。这会阻止将数组作为AnyObject处理


使用类允许我将
[Product]
传递到
performsguewithidentifier
,而无需任何类型转换,并且使用
发送者身份再次成功地转换收到的参数![产品]

谢谢亚当。我的问题通过下面的回答解决了。您的回答很好,但肯定包含一些错误,因为在最终解决方案中我根本不需要任何类型转换。我假设您的产品实体是一个类。很高兴你找到了答案!