NSArray 元素无法匹配 Swift 数组元素类型的原因

reason of NSArray element failed to match the Swift Array Element type

过去 2 小时我一直被困在这里,仍然不知道这里到底出了什么问题:

在我的后端我有值说 tables 命名为 DogsCats

我的狗 table 的一列与猫有关 table(一对多关系)

现在我正在尝试获取我的狗的值 table 但我不断收到错误消息 :

fatal error: NSArray element failed to match the Swift Array Element type

我的代码:

//object classes 
class Dogs : NSObject {
    var id : String?
    var cats : [Cats]?
}

class Cats : NSObject {
    var rats : [Rats]?
    var name : String?
}

在这里我从我的后端检索了狗 Class 然后

for dog in dogs  { // dogs is an array of Dogs Object
print(dog.id) // expected output 
print((dog.cats) // here i'm getting the error 

在调试器中 dog.cats 的值是:

id  String? "dog1"
cats    [MyPackage.ViewController.Cats]?    Some

我还通过打印 dog.cats.count 返回全部对象(预期行为)

确认猫在其中具有价值

有人知道为什么会这样吗??

您已经在 ViewController class 中声明了您的 Cats class,这意味着您的数组包含 ViewComtroller.Cats 个对象,而不是 Cats.

在他们自己的 .swift 文件中声明您的 Cats(和您的 Dogs class)

这是因为编译器会将@objc 添加到NSObject 的子类中。所以默认情况下你会得到一个 NSArray 。因此,将 @nonobjc 添加到那些您不想暴露给 Objective-C 的 property/function/class。你会得到 Swift 数组。

class Dogs : NSObject {
    var id : String?
    @nonobjc var cats : [Cats]?
}

已更新

Swift 4.

默认不添加@objc