Swift 2.2泛型问题(Xcode 7.3)

Vas*_*Vas 7 ios swift xcode7.3 swift2.2

我对Swift 2.2(Xcode 7.3)感到沮丧.要模拟它,只需在用户定义的泛型类中创建一个变量,并从其他地方引用该类.例如:

class A<T> {
    let genVar = 1
}

class MyViewController: UIViewController {
    let myVar = A<Int>() // crash is here
}
Run Code Online (Sandbox Code Playgroud)

如果您将在运行iOS 7(iPhone 4,在我的情况下)的设备上运行此代码,则会尝试创建泛型类型的变量.以下是设备崩溃日志的第一行:

Exception Type:  EXC_BAD_ACCESS (SIGBUS)
Exception Subtype: KERN_PROTECTION_FAILURE at 0x00298910
Triggered by Thread:  0

Thread 0 Crashed:
0   libswiftCore.dylib              0x006b1d64 0x4bd000 + 2051428
1   Phone                           0x001c76ec 0xab000 + 1165036
2   libswiftCore.dylib              0x006b307c 0x4bd000 + 2056316
3   libswiftCore.dylib              0x006b2f70 0x4bd000 + 2056048
4   libswiftCore.dylib              0x006b0f24 0x4bd000 + 2047780
5   libswiftCore.dylib              0x006b107c 0x4bd000 + 2048124
6   Phone                           0x0014e730 0xab000 + 669488
7   Phone                           0x00129390 0xab000 + 517008
8   UIKit                           0x31e9d9c4 -[UIClassSwapper initWithCoder:] + 188
Run Code Online (Sandbox Code Playgroud)

在iOS 8和9模拟器/设备上,上面的代码工作正常.

Swift对iOS 7的支持是否会在不久的将来被删除?

Dan*_*iel 1

如此错误所示,您有以下可能的解决方法:

  • 使类成为非泛型类
  • 删除value财产
  • 交换objectvalue属性声明
  • 初始化对象在init

最好的解决方法可能是在以下位置初始化对象init

class A<T> {
    let genVar: Int
    init() {
       genVar = 1
    }

}

class MyViewController: UIViewController {
    let myVar = A<Int>() // no crash
}
Run Code Online (Sandbox Code Playgroud)