“无法转换类型的值” - Firebase Swift 中的错误
Posted
技术标签:
【中文标题】“无法转换类型的值” - Firebase Swift 中的错误【英文标题】:"cannot convert value of type" - error in Firebase Swift 【发布时间】:2016-01-31 15:20:21 【问题描述】:我正在尝试使用电子邮件和密码在 Firebase 中创建用户,并且在成功创建用户记录后,我将使用附加属性更新树作为用户 UID 的子节点。这是我在代码中的内容:
@IBAction func registerPressed(sender: AnyObject)
let connection = Firebase(url:"https://something.firebaseio.com")
connection.createUser(self.emailTxtField.text, password: self.passwordTxtField.text,
withValueCompletionBlock: error, result in
if error != nil
// There was an error creating the account
print("Error Creating Account...Please try again")
else
let uid = result["uid"] as? String
print("Successfully created user account with uid: \(uid)")
/*After creating the user, we want to update the tree with other attributes*/
let userAdditionalDetails = ["name": self.nameTxtField.text, "mobile": self.mobileTxtField.text, "username": self.usernameTxtField.text]
let usersRef = connection.childByAppendingPath("users")
let users = ["\(uid)": userAdditionalDetails]
usersRef.setValue(users)
)
虽然不确定上述是否可行(因为这是我第一次使用 Firebase SDK),但我收到以下错误:
无法将“[String: [String : String?]]”类型的值转换为 预期的参数类型“AnyObject!”
由于上述错误被触发,我当然无法构建项目:
usersRef.setValue(users)
知道为什么会发生这种情况以及如何解决吗?
提前致谢。
【问题讨论】:
【参考方案1】:找到解决方案并将其放在这里以供其他人将来参考:
@IBAction func registerPressed(sender: AnyObject)
let connection = Firebase(url:"https://something.firebaseio.com")
connection.createUser(self.emailTxtField.text, password: self.passwordTxtField.text,
withValueCompletionBlock: error, result in
if error != nil
// There was an error creating the account
print("Error Creating Account...Please try again")
else
let uid = result["uid"] as? String
print("Successfully created user account with uid: \(uid)")
/*After creating the user, we want to update the tree with other attributes*/
let userAdditionalDetails = ["name": "\(self.nameTxtField.text!)", "mobile": "\(self.mobileTxtField.text!)", "username": "\(self.usernameTxtField.text!)"]
let usersRef = connection.childByAppendingPath("users")
let users = ["\(uid)": userAdditionalDetails]
usersRef.setValue(users)
)
需要注意的是,在初始化 userAdditionalDetails 时,应该以字符串格式包含 outlets 变量。例如。
"username": "\(username.text!)"
这行得通,所有对象都正确反映在后端。
【讨论】:
【参考方案2】:在对usersRef.setValue(users)
的调用中,错误消息指出参数应为AnyObject!
类型。因此,您必须将users
转换为AnyObject!
类型:
let users = ["\(uid)": userAdditionalDetails]
usersRef.setValue(users as? AnyObject)
【讨论】:
这是不对的,因为 users 是一个字典,你不能将它转换为 AnyObject...稍后运行时错误。以上是关于“无法转换类型的值” - Firebase Swift 中的错误的主要内容,如果未能解决你的问题,请参考以下文章
AFHTTPRequestOperation setCacheResponseBlock 无法转换类型的值