我使用斯威夫特與火力地堡和我感到困惑的這個錯誤點點價值:Could not cast value of type '__NSDictionaryM' (0x122ab6130) to 'Repeat.Expression' (0x1100004c0).
斯威夫特和火力地堡 - 無法投型「__NSDictionaryM」
這裏是JSON文件的示例中,我使用:
{
"levels" : {
"level1" : {
"coverImage" : "lvl1",
"expressions" : [ {
"expression" : "Yes",
"id" : 0
}, {
"expression" : "Yes",
"id" : 1
}, {
"expression" : "Yes",
"id" : 2
}, {
"expression" : "Yes",
"id" : 3
} ],
"id" : 0,
"title" : "Essentiel"
},
"level2" : {
...
},
}
}
這裏有兩種模式使用:
struct Level {
let id : Int
let coverImage : String
let title : String
let expressions : [Expression]
}
struct Expression {
let id : Int
let expression : String
}
最後,這裏是我用來獲取級別的功能:
var levels = [Level]()
func fetchLevels() {
FIRDatabase.database().reference().child("levels").observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
if let levelId = dictionary["id"], let levelCoverImage = dictionary["coverImage"], let levelTitle = dictionary["title"], let levelExpressions = dictionary["expressions"] {
let level = Level(
id: levelId as! Int,
coverImage: levelCoverImage as! String,
title: levelTitle as! String,
expressions: levelExpressions as! [Expression]
)
self.levels.append(level)
}
DispatchQueue.main.async{
self.collectionView?.reloadData()
}
}
}, withCancel: nil)
}
看來,這個問題是在該行expressions: levelExpressions as! [Expression]
非常感謝您的幫助。
祝您有美好的一天。
分配
Expression
對象'levelExpressions'是NSDictionaries的陣列不是你表達類;你需要從字典中顯式地創建'Expression'的實例。 – Paulw11