无法在Swift中访问多维数组

时间:2014-06-16 11:28:15

标签: swift

我创建了一个多维数组,但是当我尝试在viewDidLoad中访问它时,应用程序崩溃了。有关为何发生这种情况的任何建议吗?

我还尝试将我的数组定义为var data: KeyLabelType[][],但这也无济于事。

class MyViewController: UIViewController {

    var data: Array<Array<KeyLabelType>> = []

    init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!)  {

        let array1: KeyLabelType[] = [...]
        let array2: KeyLabelType[] = [...]
        let array3: KeyLabelType[] = [...]

        self.data = [array1, array2, array3]

        super.init(nibName: nibNameOrNil, bundle: nibBundle)
    }

    override func viewDidLoad()  {

        let count = self.data.count // Application crashes here
    }
}

enter image description here

编辑:

我将KeyLabelType声明为

enum KeyLabelType: Character {
    case a = "a"
    case b = "b"
    case c = "c"
}

编辑: 我向Apple提交了一份错误报告(17340589)

1 个答案:

答案 0 :(得分:4)

这是一个错误,请在bugreport.apple.com报告。这与swift中的NSObject子类化有关。

import Foundation

enum KeyLabelType: Character {
    case a = "a"
    case b = "b"
    case c = "c"
}

class MyClass: NSObject /* Removing NSObject here will fix the crash */ {
    var myData: Array<Array<KeyLabelType>>

    init() {
        let array1: Array<KeyLabelType> = [.a, .b]
        let array2: Array<KeyLabelType> = [.b]
        let array3: Array<KeyLabelType> = [.c]

        self.myData = [array1, array2, array3]
    }
}

var myObject = MyClass()
myObject.myData //Crash here, if subclassing NSObject. No crash if NSObject is removed

如果您可以重写代码以使用NSObject子类,那么它也可以作为一种解决方法

import Foundation

class KeyLabelType: NSObject {
    let value: Int

    init(_ value: Int) {
        self.value = value
    }

}

class MyClass: NSObject {
    var myData: NSArray

    init() {
        var item = KeyLabelType(1)
        var array1: NSArray = [KeyLabelType(1), KeyLabelType(2)]
        var array2: NSArray = [KeyLabelType(1), KeyLabelType(2)]
        self.myData = [array1, array2]
    }
}

var myObject = MyClass()
myObject.myData.count