我需要检查字典是否有钥匙。如何?


当前回答

swift 4.2解决方案

所以,如果你只想回答这个问题,字典是否包含键,问:

let keyExists = dict[key] != nil

如果你想要这个值,并且你知道字典中包含这个键,那么说:

let val = dict[key]!

但如果,就像通常发生的那样,你不知道它包含键-你想获取它并使用它,但前提是它存在-然后使用类似if let的东西:

if let val = dict[key] {
    // now val is not nil and the Optional has been unwrapped, so use it
}

其他回答

在NSDictionary中检查key是否存在:

if([dictionary objectForKey:@"Replace your key here"] != nil)
    NSLog(@"Key Exists");
else
    NSLog(@"Key not Exists");
if ([[dictionary allKeys] containsObject:key]) {
    // contains key
}

or

if ([dictionary objectForKey:key]) {
    // contains object
}
if ([mydict objectForKey:@"mykey"]) {
    // key exists.
}
else
{
    // ...
}

我建议您将查找结果存储在一个临时变量中,测试临时变量是否为nil,然后使用它。这样你就不会重复查找同一个对象:

id obj = [dict objectForKey:@"blah"];

if (obj) {
   // use obj
} else {
   // Do something else
}

因为nil不能存储在Foundation数据结构中,NSNull有时表示nil。因为NSNull是一个单例对象,你可以通过直接指针比较来检查NSNull是否是存储在字典中的值:

if ((NSNull *)[user objectForKey:@"myKey"] == [NSNull null]) { }