Serguei Fedorov
Serguei Fedorov

Reputation: 7913

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:

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.

Upvotes: 0

Views: 88

Answers (1)

Kametrixom
Kametrixom

Reputation: 14973

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 Anys might have a length of 320 bytes, but 10 Users 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 Users 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

Upvotes: 3

Related Questions