我收到此错误,我无法弄清楚如何修复:
Contextual type 'AnyObject' cannot be used with dictionary literal
我在互联网上搜索但未能找到答案。这是我的代码:
struct Sweet {
let key:String!
let content:String!
let addedByUser:String!
let itemReft:FIRDatabaseReference?
init (content:String, addedByUser:String, key:String = "") {
self.key = key
self.content = content
self.addedByUser = addedByUser
self.itemReft = nil
}
init (snapshot:FIRDataSnapshot) {
key = snapshot.key
itemReft = snapshot.ref
if let dict = snapshot.value as? NSDictionary, let postContent = dict["content"] as? String {
content = postContent
} else {
content = ""
}
if let dict = snapshot.value as? NSDictionary, let postUser = dict["addedByUser"] as? String {
addedByUser = postUser
} else {
addedByUser = ""
}
}
func toAnyObject() -> AnyObject {
return ["content":content, "addedByUser":addedByUser]
}
错误发生在这一行:
return ["content":content, "addedByUser":addedByUser]
我一直在关注本教程iOS Swift Tutorial: Get started with Firebase and an App like Twitter
谢谢你的时间!
答案 0 :(得分:1)
您必须将文字转换为所需类型
func toAnyObject() -> Any {
return ["content":content, "addedByUser":addedByUser] as Any
}
但是 - 没有冒犯 - 将特定类型转换为更具特色的东西是愚蠢的。为什么不
func toDictionary() -> [String:String] {
return ["content":content, "addedByUser":addedByUser]
}