I have got an array of objects that conform to an interface
interface SomeInterface{}
and a class that conforms to that interface
class SomeClass : NSObject, SomeInterface{}
Now, I create an array of SomeInterface objects
var myInterfaceObjects : SomeInterface[] = SomeInterface[]()
Then I would like to cast this array to a SomeClass object array
var someClassObjects : SomeClass[] = myInterfaceObjects as SomeClass[] //CRASH!
How can I downcast without a crash ?
fatal error: can't reinterpretCast values of different sizes
(lldb) bt
* thread #1: tid = 0x935ef, 0x001986b8 libswift_stdlib_core.dylib`Swift.reinterpretCast <A, B>(A) -> B + 220, queue = 'com.apple.main-thread', stop reason = EXC_BREAKPOINT (code=EXC_ARM_BREAKPOINT, subcode=0xe7ffdefe)
* frame #0: 0x001986b8 libswift_stdlib_core.dylib`Swift.reinterpretCast <A, B>(A) -> B + 220
frame #1: 0x001bebdc libswift_stdlib_core.dylib`Swift.ContiguousArrayBuffer.storesOnlyElementsOfType <A>(Swift.ContiguousArrayBuffer<A>)<B>(B.Type) -> Swift.Bool + 912
frame #2: 0x001bde08 libswift_stdlib_core.dylib`Swift._arrayCheckedDownCast <A, B>(Swift.Array<A>) -> Swift.Optional<Swift.Array<B>> + 292
frame #3: 0x00094c84 MyApp`MyApp.MyClass.(data=SomeInterface[]! at 0x27db0870, response=Foundation.NSHTTPURLResponse! at 0x27db086c, error=None, self=<unavailable>) -> (Swift.Bool) -> ()).(closure #1) + 428 at MyClass.swift:81
Sounds like a compiler bug, you should report it (as Kevin said in the comments)
For now you can try to work around it by casting the objects individually:
var someClassObjects : [SomeClass] = myInterfaceObjects.map { $0 as SomeClass }
edit: updated to the latest swift syntax. Also worth mentioning this bug may have been resolved in beta 3 or beta 4 – I haven't checked
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments