Swift 4:表达式从'[String:String?]'隐式强制为'[AnyHashable:Any]'

时间:2019-01-27 15:26:55

标签: swift firebase swift4

为什么我在一行中看到错误消息:

usersReference.updateChildValues(values, withCompletionBlock: { (err, ref)

错误消息显示:

表达式从'[String:String?]'隐式强制为'[AnyHashable:Any]'

我可以对代码进行哪些更改以防止出现错误消息?

这是我来自视图控制器的所有代码:

import UIKit
import Firebase
import FirebaseAuth

class RegisterViewController: UIViewController {

private var ref: DatabaseReference! // референс к БД

@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var firstNameField: UITextField!
@IBOutlet weak var lastNameField: UITextField!
@IBOutlet weak var cityField: UITextField!
@IBOutlet weak var telNumField: UITextField!


override func viewDidLoad() {
    super.viewDidLoad()

    ref = Database.database().reference() // инициализация БД

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}

@IBAction func nextButtonPressed(_ sender: Any) {
    Auth.auth().createUser(withEmail: self.emailField.text!, password: self.passwordField.text!) { (user, error) in

        if error != nil {
            print(error!)
            self.showAlert(title: "Error!", msg: "Invalid information", actions: nil)
            return
        }
        print("Registration succesfull")

        guard let uid = user?.uid else { //доступ к ID пользователя
            return
        }

        self.ref = Database.database().reference() // инициализация БД
        let usersReference = self.ref.child("users").child(uid)
        let values = ["firstname": self.firstNameField.text, "lastname": self.lastNameField.text, "email": self.emailField.text, "city": self.cityField.text, "telnumber": self.telNumField.text]
        usersReference.updateChildValues(values, withCompletionBlock: { (err, ref) in
            if let err = err {
                print(err)
                return
            }
            print("Saved user successfully into Firebase db")
        })
    }
}

1 个答案:

答案 0 :(得分:1)

  

我可以对代码进行哪些更改以防止出现错误消息?

这不是错误,编译器不允许您在不修复代码的情况下运行代码,这只是警告。但是此警告的消息很重要,因为如果不修复它,则字符串将像这样保存:

Optional("Text from text field")

因此,在您的情况下,您正在将text类型的String?的可选属性Any作为text传递。

您可以通过强制展开文本字段的nil属性来消除此警告并修复代码(在此处强制展开它是安全的,因为对于docs而言,此属性永远不会{ {1}})

let values = ["firstname": self.firstNameField.text!, "lastname": self.lastNameField.text!, "email": self.emailField.text!, "city": self.cityField.text!, "telnumber": self.telNumField.text!]