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


当前回答

if ([[dictionary allKeys] containsObject:key]) {
    // contains key
}

or

if ([dictionary objectForKey:key]) {
    // contains object
}

其他回答

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 ([mydict objectForKey:@"mykey"]) {
    // key exists.
}
else
{
    // ...
}

正如Adirael建议objectForKey检查键的存在,但当你调用objectForKeyin可空字典时,应用程序崩溃,所以我从下面的方式修复了这个问题。

- (instancetype)initWithDictionary:(NSDictionary*)dictionary {
id object = dictionary;

if (dictionary && (object != [NSNull null])) {
    self.name = [dictionary objectForKey:@"name"];
    self.age = [dictionary objectForKey:@"age"];
}
return self;

}

if ([[dictionary allKeys] containsObject:key]) {
    // contains key
}

or

if ([dictionary objectForKey:key]) {
    // contains object
}

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