简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM