循环填充数组时Swift EXC_BAD_INSTRUCTION

时间:2014-11-12 18:35:23

标签: arrays swift swift-playground

let P: UInt32 = 0xB7E15163
let Q: UInt32 = 0x9E3779B9 
let r = 20

var S:[UInt32] = Array(count: 2*r+4, repeatedValue: 0)

S[0] = P;


for i in 1...2*r+3 {
    S[i] = S[i-1] + Q
}

错误发生在结束括号所在的代码的最后一行。不知道为什么我会收到这个错误,如果有人可以提供帮助,那将非常感激。

thread #1: tid = 0x11615, 0x000000011ae465ed $__lldb_expr359`__lldb_expr_359.generateKeys () -> Swift.Array<Swift.UInt32> + 4509 at playground359.swift:30, queue = 'com.apple.main-thread', stop reason = EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
  * frame #0: 0x000000011ae465ed $__lldb_expr359`__lldb_expr_359.generateKeys () -> Swift.Array<Swift.UInt32> + 4509 at playground359.swift:30
    frame #1: 0x000000011ae4538e $__lldb_expr359`top_level_code + 910 at playground359.swift:51
    frame #2: 0x000000011ae46831 $__lldb_expr359`main + 49 at <EXPR>:0
    frame #3: 0x000000010eedc510 RC6`get_field_types__XCPAppDelegate + 160
    frame #4: 0x000000010eedd081 RC6`reabstraction thunk helper from @callee_owned () -> (@unowned ()) to @callee_owned (@in ()) -> (@out ()) + 17
    frame #5: 0x000000010eedbcf1 RC6`partial apply forwarder for reabstraction thunk helper from @callee_owned () -> (@unowned ()) to @callee_owned (@in ()) -> (@out ()) + 81
    frame #6: 0x000000010eedd0b0 RC6`reabstraction thunk helper from @callee_owned (@in ()) -> (@out ()) to @callee_owned () -> (@unowned ()) + 32
    frame #7: 0x000000010eedd0e7 RC6`reabstraction thunk helper from @callee_owned () -> (@unowned ()) to @callee_unowned @objc_block () -> (@unowned ()) + 39
    frame #8: 0x000000010f524abc CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 12
    frame #9: 0x000000010f51a805 CoreFoundation`__CFRunLoopDoBlocks + 341
    frame #10: 0x000000010f519fc3 CoreFoundation`__CFRunLoopRun + 851
    frame #11: 0x000000010f519a06 CoreFoundation`CFRunLoopRunSpecific + 470
    frame #12: 0x000000010f5c62c1 CoreFoundation`CFRunLoopRun + 97
    frame #13: 0x000000010eed9dcd RC6`top_level_code + 3629
    frame #14: 0x000000010eedc53a RC6`main + 42
    frame #15: 0x00000001121f7145 libdyld.dylib`start + 1

2 个答案:

答案 0 :(得分:0)

对于i = 1

的结果
S[1] = S[0] + Q = 0xB7E15163 + 0x9E3779B9

无法表示为UInt32,因此程序会中止。

如果你想在(Objective-)C中添加“溢出”或“环绕”,你必须这样做 明确指定“溢出运算符”&+

S[i] = S[i-1] &+ Q

有关更多信息,请参阅Swift文档中"Advanced Operators"中的“溢出运算符”。

答案 1 :(得分:-1)

我已经使用所有UInt64对该程序进行了测试,效果很好。 希望有所帮助;)