我有以下代码崩溃。
class PersonFactory {
class var build: PersonInterface {
get {
return Person()
}
}
}
class Person: PersonInterface {
var age: Int = 0
func say(message: String) {
print(message)
}
}
protocol PersonInterface: class {
var age: Int { get set }
func say(message: String)
}
当我从 view controller 运行以下行时它崩溃了:
PersonFactory.build.say("hello")
在以下行 var age: Int = 0
上因 EXC_BAD_ACCESS
而崩溃。该问题出现在 Xcode 7 beta 4 (7A165t) 中。
请注意,代码不会在 Playground 中崩溃,只有在从应用调用时才会崩溃。这是演示应用程序:https://github.com/exchangegroup/ProtocolCrashDemo
注意:定义 PersonFactory、Person 和 PersonInterface 的代码应该放在单独的文件中,以免崩溃。
看起来像是 Swift 2.0 的错误?我向 Apple 提交了错误报告。
更新
该问题已在 Xcode 7.0 beta 5 中修复。
最佳答案
您可以通过这样做来避免此崩溃:
import Foundation
class PersonFactory<T: PersonInterface> {
class var build: T {
return T()
}
}
class Person: PersonInterface {
var age: Int
required init() {
age = 0
}
func say(message: String) {
print(message)
}
}
protocol PersonInterface {
init()
var age: Int { get set }
func say(message: String)
}
let person: Person = PersonFactory.build
person.say("hello")
关于Xcode 7 beta swift 应用程序在运行时崩溃并出现 EXC_BAD_ACCESS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31020305/