2017-01-22 64 views
1

我有以下火力地堡数据结构:如何更新/添加项目到Firebase中的JSON数组?

"Group" : { 
    "34923493" : { 
    "Name" : "Group 1" 
    "Users" : { 
     joeshmoe : true 
     janedoe : true 
    } 
    etc..... 
    } 
} 

欲以下添加到“用户”部分:

johndoe : true 

当用户已经加入该组。我有以下代码

self.ref.child("Group").child(groupID!).child("Users").setValue([user?.username : true]) 

,但我得到了以下错误:

"Contextual type'Any' cannot be used with dictionary literal" 

我不知道我的做错了吗?

回答

0

代码中有两件事是错误的。

  1. 你得到的错误很可能是由成员变量username存在Any型引起的。因此,简单地把它向下转换到String

    [user?.username as! String: true] 
    
  2. 此行

    self.ref.child("Group").child(groupID!).child("Users").setValue([user?.username : true]) 
    

    将删除从字典中的所有其他用户。你可以将[user?.username: true]分配给那个孩子,删除已经存在的字典值。 更新字典的关键,而不是直接如下:

    self.ref.child("Group").child(groupID!).child("Users").child(user?.username as! String).setValue(true)