我收到这个错误,我不知道如何修复:
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
感谢您的宝贵时间!
最佳答案
您必须将文字转换为所需的类型
func toAnyObject() -> Any {
return ["content":content, "addedByUser":addedByUser] as Any
}
但是 - 无意冒犯 - 将特定类型转换为更不特定的类型是愚蠢的。为什么不
func toDictionary() -> [String:String] {
return ["content":content, "addedByUser":addedByUser]
}
关于ios - Swift Firebase - 上下文类型 'AnyObject' 不能与字典文字一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39688076/