I am trying to check if an input from a textfield exists in the NSDictionary but I am not sure how to do this.
let nsdict = snapshot.value as? NSDictionary
let values = nsdict?.allValues
Once I Do this i am not sure on how to cast the values to a string to check with a user input textfield.
For example doing this:
if values.contains(userIinput.text){
print("Found")
}
答案 0 :(得分:1)
You can apply a filter. In the following code I create a dictionary, and then I filter looking for the userInput.text. Every value that matches will get stored in the new dictionary matches. If matches is > 0, the input already exists and you will have a dictionary with the keys that have the userInput.text as value. Also, you can check if it matches more than once. You need to verify that $0.value is an String or that the userInput is not nil because if the user input is nil and the $0.value of the dictionary is not an String it will be will and return a match.
let dict: [String : Any] = ["first" : "String", "Second" : 2]
let matches = dict.filter{
guard let value = $0.value as? String else { return false }
value == userInput.text
}
matches.count
If you just want to check if it already exists you can just
guard let userInput = userInput else { return }
if (!dict.filter{ $0.value as? String == userInput }.isEmpty) {
print ("Found")
}
In the first example I'm verifying that $0.value is an String if not I am returning that it does not match, and in the second I am checking that the userInput is not nil, if not it finishes the function there (you can use and if let if you prefer)