无法输入类型的值NSNull'来自NSDictionary'

时间:2017-08-31 04:24:22

标签: ios swift xcode dictionary swift3

我收到的错误是#34; self.email =(snapshot.value as!NSDictionary)[" email"] as!字符串"说它不能铸造类型的价值' NSNull'。我该如何修复错误?我认为,因为我有一个函数toAnyObject,它会将所有内容转换为String。

struct User {
    var email: String!
    var uid: String!
    var ref: DatabaseReference!
    var key: String = ""

    init(snapshot: DataSnapshot) {
        self.email = (snapshot.value as! NSDictionary)["email"] as! String
        self.uid = (snapshot.value as! NSDictionary)["uid"] as! String
        self.ref = snapshot.ref
        self.key = snapshot.key
    }

    init(email: String, uid: String) {
        self.email = email
        self.uid = uid
        self.ref = Database.database().reference()
    }

    func toAnyObject() -> [String: Any] {
        return ["email":self.email, "uid":self.uid]
    }
}

2 个答案:

答案 0 :(得分:3)

正如El Captain v2.0指出的那样,不要强制打开一个值,因为它可能是nil并且你会崩溃。请改用if let

// if snap has a value, then you can use the value. Otherwise not, you can call an else if you want to.
if let snap = snapshot.value as? [String:Any] { 
    self.email = snap["email"] as! String 
}

我也会跳过as! String并且会这样做,而不是你得到email值。

if let snap = snapshot.value as? [String:Any], let email = snap["email"] as? String  { 
    // Use email in here now
    print(email)
}

因此,如果您想要获得其他字段,只需将其添加到if-statement

答案 1 :(得分:0)

    struct User {

    var email: String!
    var uid: String!
    var ref: DatabaseReference!
    var key: String = ""

    init(snapshot: DataSnapshot){

        self.email = (snapshot.value as! NSDictionary)["email"] as! String
        self.uid = (snapshot.value as! NSDictionary)["uid"] as! String
        self.ref = snapshot.ref
        self.key = snapshot.key

    }

    init(email: String, uid: String){

        if let snap = snapshot.value as? [String:Any] {
        // Do not unwrap forcefully, instead use as mentioned below 
        // so that in case snap["email"] gives null that could be 
        //handled. 
        //Also please check that whether you have "firstname" var 
        //present in not in your code and dictionary both. 
        self.email = snap["email"] as? String ?? "" //Provide some default value or empty string
        }
        self.uid = uid
        self.ref = Database.database().reference()

    }

    func toAnyObject() -> [String: Any]{
        return ["email":self.email, "uid":self.uid]
    }
    }