Swift Binary operator '+ =' cannot be applied to operands of type "AnyObject!" and 'String!'
I want to add the current username of the user at the end of an object Participants
in Parse using Swift, but I got an error in the header.
obj["Participants"] += kCurrentUser.username
I don't know how to fix this. I have already tried .append
some other methods. Do you have any ideas?
It looks like obj is an NSDictionary. NSDictionaries contain anonymous values ββfor each key. Therefore, when you view the key, the value is of type AnyObject. You cannot add a line to AnyObject.
You will need to use a more verbose statement:
obj["Participants"] = obj["Participants"] as! String + kCurrentUser.username
(This will only work if obj is a mutable dictionary. If it is immutable, it will work.)
Swift does not perform implicit conversion, if two operands are of different types, you need to convert either of them to a different operand type in order to apply the binary operator.
So, in your case, convert the operand from type AnyObject to String.
Only a couple of weeks in swift was amazed by this, but as mentioned, "Swift Language doesn't do implicit type conversion, .."
For me, I had this code:
if objects == nil {
objects = NSMutableArray()
}
Converted to:
if objects.count == 0 {
objects = NSMutableArray()
}