简体   繁体   English

快速转换通用数组会导致致命错误

[英]Casting generic array in swift cause fatal error

I have a class which acts as a BLL, wrapping a service protocol. 我有一个充当BLL的类,包装了服务协议。 The service protocol provides a list of SerializableObjectProtocol objects. 服务协议提供了SerializableObjectProtocol对象的列表。 For instance, I have User , which implements SerializedObjectProtocol . 例如,我有User ,它实现了SerializedObjectProtocol

The following function casts a SerializedObjectProtol array into a User 以下函数将SerializedObjectProtol数组强制转换为User

public func Get() -> [T]
{
    let result = self._service.Get()

    return result as! [T]
}

As a result, I am getting the following error: 结果,出现以下错误:

 array element cannot be bridged to Objective-C

I am aware that the code is error prone, because if the object is not T, down casting cannot happen. 我知道代码很容易出错,因为如果对象不是T,就不会发生向下转换。 As a result, here is what I can verify: 结果,这是我可以验证的:

  • T in constrained to implement SerializedObjectProtol ie T in约束以实现SerializedObjectProtol,即

      class DataLayer<T:SerializableObjectProtocol> 
  • T is type User. T是用户类型。 The result is an array of user. result是一个用户数组。 ie [User] [User]

  • I can get around this issue, but I have to manually cast each item. 我可以解决这个问题,但是我必须手动投射每个项目。 As a result, this works perfectly fine: 结果,这工作得很好:

     var returnArray = [T]() for item in result { returnArray.append(item as! T) } return returnArray; 

I have just picked up Swift for a project so I have limited experience with it. 我刚刚为项目选择了Swift,所以我的经验有限。 As a result, I have gone out to see if what I am trying is possible (casting array [S] to [T]). 结果,我出去看看我在尝试什么(将数组[S]投射到[T])。 It seems that it is possible if the array is [Any] . 如果数组为[Any] ,则似乎是可能的。

Is this a valid operation in Swift? 这是Swift中的有效操作吗? Or is casting this way not possible. 还是无法通过这种方式进行投射。

Generally it is not possible to cast directly between an array of Any to the type it contains, because Any has a completely different representation in memory: sizeof(Any) isn't equal to sizeof(User) ! 通常,不可能在Any数组之间直接转换为其包含的类型,因为Any在内存中具有完全不同的表示形式: sizeof(Any)不等于sizeof(User) An array of 10 Any s might have a length of 320 bytes, but 10 User s only need 80 bytes, the same applies to any protocol. 由10个Any的数组可能具有320个字节的长度,但是10个User只需80个字节,这对任何协议都适用。 Conclusion: You need to cast every single item. 结论:您需要转换每个项目。

Maybe do it like this: 也许这样做:

return results.map{ $0 as! User }

or if you're not sure whether every item is a User , you can only return the User s like this: 或者,如果不确定每个项目是否都是User ,则只能返回User如下所示:

return results.flatMap{ $0 as? User }

If you're still having problems, please post some minimal code that still produces the error, it's really hard to understand what your code looks like without the actual code 如果仍然有问题,请发布一些仍会产生错误的最小代码,如果没有实际代码,很难理解您的代码是什么样的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM