[英]fatal error: NSArray element failed to match the Swift Array Element type
[英]reason of NSArray element failed to match the Swift Array Element type
我從過去2個小時就被困在這里仍然不知道這里到底是怎么回事:
在我的后端,我有價值觀說有名為Dogs
和Cats
表
我的狗桌的一欄與貓桌有關(一對多的關系)
現在我正試圖獲取我的狗表的值,但我不斷得到變薄的錯誤:
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.