why am i getting this error at the line " let postObject = [String:AnyObject] = [ "
Cannot assign to value: function call returns immutable value
@IBAction func HandleSendButton(_ sender: Any) {
let postRef = Storage.storage().reference().child("messages").child("\(selectedUser).[“id”]")
let postObject = [[String:AnyObject]]() = [
"From": [
"uid": User.uid,
"username": User.username,
"photoURL": User.photoURL.absoluteString
],
"Message": textView.text,
"timestamp": [".sv":"timestamp"]
] as [String:Any]
postRef.setValue(postObject, withCompletionBlock: { error, ref in
if error == nil {
self.dismiss(animated: true, completion: nil)
} else {
// Handle the error
}
})
}
Just remove the = [[String:AnyObject]]()
part:
let postObject = [
or
let postObject: [String: Any] = [
It's supposed to be like this:
let postObject: [[String: Any]] = [[
"From": [
"uid" : User.uid,
"username" : User.username,
"photoURL" : User.photoURL.absoluteString
],
"Message" : textView.text,
"timestamp" : [".sv" : "timestamp"]
]]
let postObject
part declares a constant, : [[String:AnyObject]]
declares its type (notice that not using =
), and finally after =
is the literal object that initializes it.
There are a few issues to be addressed.
Let's assume your Firebase looks like this
root
questions
uid_0
From:
photoUrl: "some photoUrl"
uid: "some userid"
username: "some username"
message: "some message"
timestamp: "some timestamp"
If you want to create a new questions node this will create it in that structure
let uid = Auth.auth().currentUser?.uid
let postRef = self.ref.child("questions").child(uid!) //self.ref is a class var*
let dict: [String: Any] = ["From":
["uid": "some uid",
"username": "some username",
"photoUrl": "some url"],
"message": "some message",
"timestamp": "some timestamp"
]
postRef.setValue(dict, withCompletionBlock: { error, ref in
if error == nil {
self.dismiss(animated: true, completion: nil)
} else {
// Handle the error
}
})
With this, we get the uid and define the reference to where the data is written.
Then the simple use of a dictionary; Firebase uses key: value pairs to store it's data and we define a dictionary to contain a key, which is a String and the values can be a kind of Any.
let dict: [String: Any]
That allows the first element to be a String: Dictionary, and the second and third elements to be String: String.
*self.ref points to my root Firebase node. Edit to point to yours.
Try this:
let postObject: [String: Any] = [
"From": [
"uid": User.uid,
"username": User.username,
"photoURL": User.photoURL.absoluteString
] as [String: Any],
"Message": textView.text,
"timestamp": [".sv":"timestamp"]
] as [String: Any]
The necessary changes are:
Let me know if this works for you.
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.