繁体   English   中英

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

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

我从过去2个小时就被困在这里仍然不知道这里到底是怎么回事:

在我的后端,我有价值观说有名为DogsCats

我的狗桌的一栏与猫桌有关(一对多的关系)

现在我正试图获取我的狗表的值,但我不断得到变薄的错误:

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?
}

在这里,我从我的后端检索狗类,之后

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类中声明了Cats类,这意味着您的数组包含ViewComtroller.Cats对象,而不是Cats

在自己的.swift文件中声明你的Cats (和你的Dogs类)

这是因为编译器会将@objc添加到NSObject子类中。 所以你默认会得到一个NSArray。 因此,将@nonobjc添加到您不希望暴露给Objective-C的属性/函数/类中。 你会得到Swift Array。

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

更新

默认情况下,它不会在Swift 4中添加@objc。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM