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


当前回答

在NSDictionary中检查key是否存在:

if([dictionary objectForKey:@"Replace your key here"] != nil)
    NSLog(@"Key Exists");
else
    NSLog(@"Key not Exists");

其他回答

if ([MyDictionary objectForKey:MyKey]) {
      // "Key Exist"
} 

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
}
if ( [dictionary[@"data"][@"action"] isKindOfClass:NSNull.class ] ){
   //do something if doesn't exist
}

这是针对嵌套的字典结构

如果键不存在,objectForKey将返回nil。

在NSDictionary中检查key是否存在:

if([dictionary objectForKey:@"Replace your key here"] != nil)
    NSLog(@"Key Exists");
else
    NSLog(@"Key not Exists");