如何判断文本框输入字符串是否存在于NSDictionary中
Hey Dan! I see you're trying to match your text field input against values in an NSDictionary, and hitting a snag with the contains method—let's fix that step by step.
The core issue here is that allValues from an NSDictionary returns an array of [Any], not [String], so you can't directly compare it to your text field's String input. Plus, we need to handle all the optional values safely to avoid crashes. Here's how to do it properly:
Step 1: Safely Unwrap Your NSDictionary
First, make sure you're safely accessing the dictionary and its values without force-unwrapping (which can cause crashes if the snapshot value isn't an NSDictionary):
guard let nsdict = snapshot.value as? NSDictionary else { // Handle the case where the snapshot isn't an NSDictionary print("Snapshot isn't an NSDictionary") return }
Step 2: Convert All Values to a String Array
Use compactMap to convert the [Any] array from allValues into a [String] array—this will automatically filter out any values that can't be converted to a String:
let stringValues = nsdict.allValues.compactMap { $0 as? String }
Step 3: Get and Validate the Text Field Input
Your text field's text property is optional, so unwrap it safely too. You can use a default empty string if it's nil:
guard let userInputText = userInput.text, !userInputText.isEmpty else { // Handle empty or nil input print("Input is empty or nil") return }
Step 4: Check for a Match
Now you can use the contains method on the stringValues array to see if the input exists:
if stringValues.contains(userInputText) { print("Found!") } else { print("Not found") }
Bonus: Ignore Case Sensitivity
If you want the match to be case-insensitive (e.g., "hello" matches "Hello"), modify the check like this:
if stringValues.contains(where: { $0.caseInsensitiveCompare(userInputText) == .orderedSame }) { print("Found (case-insensitive)!") }
Putting it all together, your code would look like this:
guard let nsdict = snapshot.value as? NSDictionary else { print("Snapshot isn't an NSDictionary") return } let stringValues = nsdict.allValues.compactMap { $0 as? String } guard let userInputText = userInput.text, !userInputText.isEmpty else { print("Input is empty or nil") return } if stringValues.contains(userInputText) { print("Found!") } else { print("Not found") }
That should solve your issue! The key was converting the generic [Any] values to a String array so you can properly compare with your text field input.
内容的提问来源于stack exchange,提问作者Dan

