Adrien Zier Adrien Zier - 2 months ago 16
Swift Question

Swift Firebase - Contextual type 'AnyObject' cannot be used with dictionary literal

I'm getting this error which I can't figure out how to fix:

Contextual type 'AnyObject' cannot be used with dictionary literal


I've searched on the internet but failed to find an answer. Here's my code:

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


The error happens at this line:

return ["content":content, "addedByUser":addedByUser]


I've been following this tutorial iOS Swift Tutorial: Get started with Firebase and an App like Twitter

Thanks for your time!

Answer

You have to cast the literal to the desired type

func toAnyObject() -> Any {
  return ["content":content, "addedByUser":addedByUser] as Any
}

But - no offense – casting up a specific type to something more unspecific is silly. Why not

func toDictionary() -> [String:String] {
  return ["content":content, "addedByUser":addedByUser]
}
Comments