在Swift 4

时间:2018-12-07 19:42:39

标签: ios arrays swift dictionary optional

我有此代码

let dic = snapshot.value as! [String:[String:Any]]
Array(dic.values).forEach {
    print($0["fcmToken"])
}

它产生这三个

Optional(c1DdtdDF1Rs:APA91bGJBUD65nidQiFDO90AVNgq0wiMjUaZmZXVJ8c_tYmFe5dkmgweOdO10jzPRlMVZF_qNyWMMsu7EhA5IMVo3jLWvBThDteR7WWUPqau-ZFAHKQPHgI5Vb48vA-_4nwkZCKrOVoT)
Optional(c1DdtdDF1Rs:APA91bGJBUD65nidQiFDO90AVNgq0wiMjUaZmZXVJ8c_tYmFe5dkmgweOdO10jzPRlMVZF_qNyWMMsu7EhA5IMVo3jLWvBThDteR7WWUPqau-ZFAHKQPHgI5Vb48vA-_4nwkZCKrOVoT)
Optional(c1DdtdDF1Rs:APA91bGJBUD65nidQiFDO90AVNgq0wiMjUaZmZXVJ8c_tYmFe5dkmgweOdO10jzPRlMVZF_qNyWMMsu7EhA5IMVo3jLWvBThDteR7WWUPqau-ZFAHKQPHgI5Vb48vA-_4nwkZCKrOVoT)

我想遍历它们并添加一个简单的if-check。

我尝试了

let dic = snapshot.value as! [String:[String:Any]]
Array(dic.values).forEach {
    print($0["fcmToken"])

    if($0["fcmToken"] != fcmToken) {
        print("token is not match detected")
    }

}

我不断得到

  

二进制运算符'!='不能应用于类型为'Any?'的操作数和“字符串?”

如何进一步调试呢?

2 个答案:

答案 0 :(得分:1)

您有:

let dic = snapshot.value as! [String:[String:Any]]
Array(dic.values).forEach {
    print($0["fcmToken"])
    if($0["fcmToken"] != fcmToken) {
        print("token is not match detected")
    }
}

但这给您一个编译错误。 假设这条线在工作:

let dic = snapshot.value as! [String:[String:Any]]

我会这样写其余的东西:

for v in dic.values {
    if let token = v["fcmtoken"] as? String, token != fcmtoken {
        print("token \(token) is not match detected")
    }
}

效果相同,没有错误。

答案 1 :(得分:0)

您可以尝试

let dic = snapshot.value as! [String:[String:Any]]
let tokens = Array(dic.values).map { $0["fcmToken"] as! String }
let exists = tokens.contains(fcmToken)

您的问题$0["fcmToken"]属于类型Any?,无法与类型String?fcmToken)进行比较


let dic = snapshot.value as! [String:[String:Any]]
Array(dic.values).forEach {
    print($0["fcmToken"])

    if let token =  $0["fcmToken"] as? String , token != fcmToken {
        print("token is not match detected")
    }

   // or

    if  ($0["fcmToken"] as? String) != fcmToken {
        print("token is not match detected")
    }

}

您可以节省使用

guard let dic = snapshot.value as? [String: [String:Any]] else {
  return
}

,但当值为nil时将不起作用