在运行看起来非常安全的 swift 代码时,我遇到了一个奇怪的 Bus Error
。我试图将其简化为最小的测试用例,如下所示:
Apple Swift version 2.2-dev (LLVM 3ebdbb2c7e, Clang f66c5bb67b, Swift 0ddf238ad7)
Target: x86_64-apple-macosx10.9
这段代码:
public enum MyError: ErrorType {
case SomeError(code: Int)
}
public typealias MyType = () throws -> Bool
public class Foo {
var a:MyType = { () throws -> Bool in
print("A")
return true
}
var b:MyType = { () throws -> Bool in
print("B")
return true
}
var c:MyType = { () throws -> Bool in
print("C")
throw MyError.SomeError(0)
}
}
public func handle<T>(test:T) {
let mirror = Mirror(reflecting: test)
print(mirror.subjectType)
for child in mirror.children {
if let callable = child.value as? MyType {
do {
try callable()
}
catch MyError.SomeError(let id) {
print(id)
}
catch {
print("unknown error")
}
}
}
}
let foo = Foo()
handle(foo)
生成此输出:
Foo
A
B
C
Bus error: 10
在调试器中运行它工作正常,所以我认为它与运行时的计时问题有关。
我是否在这段代码中做了一些非法或不安全的事情?
异常在闭包中是否非法?
是什么导致了这个错误?
编辑:
我现在在 swift 问题跟踪器上为此创建了一个错误:https://bugs.swift.org/browse/SR-324
最佳答案
What's causing this error?
错误不会发生,直到你到达最后一个闭包:
var c:MyType = { () throws -> Bool in
print("C")
throw MyError.SomeError(0)
}
显然,您在这里抛出异常,我怀疑问题与遍历 children
关系不大,而更多地与在迭代时抛出异常有关.我尝试在不迭代的情况下调用 c
:
public func trythis() {
let foo = Foo()
do {
try (foo.c)()
}
catch MyError.SomeError(let id) {
print(id)
}
catch { print("unknown") }
}
trythis()
然后发现它工作正常。我还尝试从 c
中删除 throw
:
var c:MyType = { () throws -> Bool in
print("C")
// throw MyError.SomeError(code: 0)
return true
}
并发现代码在那种情况下工作正常。因此,这是在遍历列表时抛出问题的组合,这让我怀疑这只是一个编译器错误,或者 Mirror
类可能存在一些问题。
我认为您应该为此向 Apple 提交错误报告。
关于swift - 为什么迭代闭包会导致 swift 出现总线错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34146985/