简体   繁体   中英

Casting generic array in swift cause fatal error

I have a class which acts as a BLL, wrapping a service protocol. The service protocol provides a list of SerializableObjectProtocol objects. For instance, I have User , which implements SerializedObjectProtocol .

The following function casts a SerializedObjectProtol array into a 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. As a result, here is what I can verify:

  • T in constrained to implement SerializedObjectProtol ie

      class DataLayer<T:SerializableObjectProtocol> 
  • T is type User. The result is an array of user. ie [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. As a result, I have gone out to see if what I am trying is possible (casting array [S] to [T]). It seems that it is possible if the array is [Any] .

Is this a valid operation in 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) ! 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. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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