You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何判断文本框输入字符串是否存在于NSDictionary中

Check if Text Field Input Exists in NSDictionary Values

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:08:58