我有一个符合接口的对象数组
interface SomeInterface{}
和一个符合该接口的类
class SomeClass : NSObject, SomeInterface{}
现在,我创建一个SomeInterface对象数组
var myInterfaceObjects : SomeInterface[] = SomeInterface[]()
然后我想将此数组转换为SomeClass对象数组
var someClassObjects : SomeClass[] = myInterfaceObjects as SomeClass[] //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
答案 0 :(得分:5)
听起来像编译器错误,你应该报告它(正如Kevin在评论中所说)
现在,您可以尝试通过单独转换对象来解决它:
var someClassObjects : [SomeClass] = myInterfaceObjects.map { $0 as SomeClass }
编辑:更新为最新的swift语法。另外值得一提的是这个bug可能已在beta 3或beta 4中得到解决 - 我还没有检查过