Xcode 7 beta swift 应用程序在运行时崩溃并出现 EXC_BAD_ACCESS 错误

标签 xcode swift

我有以下代码崩溃。

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/

相关文章:

swift - 结构成员初始化 - 省略具有默认值的属性的值

objective-c - 不断更新TableView中单元格内的数据

ios - 不同iOS版本之间的应用程序迁移

ios - 构建在一天中第一次运行时停止并显示 Restore the connection to "iPhone 5"and run "Quiz"again

ios - Xcode 模拟器 : how to remove older unneeded devices?

ios - 更改导航栏的 alpha 值以便底层对象可见

swift - Xcode 13 beta 5 错误 : UIViewController is missing its initial trait collection populated during initialization

html - 在 iOS 中的 UITableViewCell 上渲染 HTML

ios - 奇怪的 Xcode 签名问题

ios - Facebook iOS Swift SDK : Not getting callback