将词典存储到Firebase中?

时间:2015-05-13 18:18:06

标签: ios swift firebase nsdictionary

我有一个Firebase实例,我想在其中存储我想要存储到firebase中的值的字典。我查看了文档https://www.firebase.com/docs/ios/guide/saving-data.html作为参考,但似乎无法使其工作。以下是我的尝试:

    //Declared above are the currentUser values as so:
    var currentUserFirstName: String!
    var currentUserLastName: String!
    var currentUserObjectID: String!

    var attendeesArray = ["objectID": currentUserObjectID, "name": currentUserFirstName + " " + currentUserLastName]
    var eventRefChild = EventReference.childByAutoId()
    eventRefChild.setValue([
        "eventName":eventName.text,
        "attendees": attendeesArray,
        "eventCreator": currentUserFirstName 
        ])

但是当我尝试Could not find an overload for '+' that accepts the supplied arguments并且我真的不太确定为什么会遇到这个问题时,我一直收到错误说:eventRefChild.setValue([...。任何帮助将不胜感激!

编辑:变量EventReference的分配如下:EventReference = Firebase(url:"<Insert Firebase URL>")

currentUserFirstNamecurrentUserLastName内部是从Facebook抓取的个人名字和姓氏,所以它分别看起来像Bob Smith

1 个答案:

答案 0 :(得分:7)

您的代码没有任何问题。问题是正在加载到

中的值
var currentUserFirstName: String!
var currentUserLastName: String!

作为测试,我使用以下代码创建了一个示例项目,该代码与您发布的代码重复,但正常的字符串已加载到var中:

    var myRootRef = Firebase(url:"https://myproject.firebaseIO.com/")

    var currentUserFirstName = "Test"
    var currentUserLastName = "User"
    var currentUserObjectID = "object ID"

    var attendeesArray = ["objectID": currentUserObjectID, "name": currentUserFirstName + " " + currentUserLastName]
    var eventRefChild = myRootRef.childByAutoId()
    eventRefChild.setValue([
        "eventName": "eventName",
        "attendees": attendeesArray
        ])

项目已正确编译并运行,预期数据将写入Firebase。请注意,eventName.text也替换为字符串,但这不会影响答案。

调查需要转向var中加载的内容,答案是其中一个var,currentUserFirstName或currentUserLastName正在加载一个OBJECT(类),不是一个字符串。

作为旁注,为什么var被声明为隐式解包的选项(!)

编辑:添加其他信息以处理选项

if let actualString = currentUserFirstName {
    println(actualString) //proceed working with the the optional string
}
else {
    return // something bad happened! currentUserFirstName does not contain a string
}

要防止代码在可选项不包含任何值时出错,请在代码串联行的正上方添加上述代码。这里发生的是我们将currentUserFirstName(可选var)中的字符串分配给实际字符串(标准的,非可选的var)。

如果表达式的计算结果为true,那么我们可以继续评估currentUserFirstName。

如果它为false,则currentUserFirstName不包含字符串,因此优雅地处理错误。