我需要检查字典是否有钥匙。如何?
当前回答
一个非常严重的问题,浪费了我调试的时间-你可能会发现自动完成提示你尝试使用doesContain,这似乎是有效的。
除此之外,doesContain使用id比较而不是objectForKey使用的散列比较,所以如果你有一个字符串键的字典,它将返回NO给doesContain。
NSMutableDictionary* keysByName = [[NSMutableDictionary alloc] init];
keysByName[@"fred"] = @1;
NSString* test = @"fred";
if ([keysByName objectForKey:test] != nil)
NSLog(@"\nit works for key lookups"); // OK
else
NSLog(@"\nsod it");
if (keysByName[test] != nil)
NSLog(@"\nit works for key lookups using indexed syntax"); // OK
else
NSLog(@"\nsod it");
if ([keysByName doesContain:@"fred"])
NSLog(@"\n doesContain works literally");
else
NSLog(@"\nsod it"); // this one fails because of id comparison used by doesContain
其他回答
使用Swift,它将是:
if myDic[KEY] != nil {
// key exists
}
if ([MyDictionary objectForKey:MyKey]) {
// "Key Exist"
}
一个非常严重的问题,浪费了我调试的时间-你可能会发现自动完成提示你尝试使用doesContain,这似乎是有效的。
除此之外,doesContain使用id比较而不是objectForKey使用的散列比较,所以如果你有一个字符串键的字典,它将返回NO给doesContain。
NSMutableDictionary* keysByName = [[NSMutableDictionary alloc] init];
keysByName[@"fred"] = @1;
NSString* test = @"fred";
if ([keysByName objectForKey:test] != nil)
NSLog(@"\nit works for key lookups"); // OK
else
NSLog(@"\nsod it");
if (keysByName[test] != nil)
NSLog(@"\nit works for key lookups using indexed syntax"); // OK
else
NSLog(@"\nsod it");
if ([keysByName doesContain:@"fred"])
NSLog(@"\n doesContain works literally");
else
NSLog(@"\nsod it"); // this one fails because of id comparison used by doesContain
因为nil不能存储在Foundation数据结构中,NSNull有时表示nil。因为NSNull是一个单例对象,你可以通过直接指针比较来检查NSNull是否是存储在字典中的值:
if ((NSNull *)[user objectForKey:@"myKey"] == [NSNull null]) { }
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
}
推荐文章
- 在实现API时,我如何避免在块中捕获自我?
- 从另一个应用程序打开设置应用程序
- 使用NSURLSession发送POST请求
- 如何更改导航栏上“后退”按钮的标题
- 有没有办法从UITableView中移除分隔线?
- 如何在Objective-C中声明类级属性?
- 在Objective-C中@property保留,赋值,复制,非原子
- 我如何在NSAttributedString中创建一个可点击的链接?
- 停止UIWebView垂直“弹跳”?
- 对未渲染的视图进行快照,结果是一个空快照
- 开始使用instancetype而不是id是否有益?
- 我可以强制UITableView隐藏分隔符之间的空单元格吗?
- 为什么Objective-C文件使用。m扩展名?
- Objective-C for Windows
- 获得推送通知,而应用程序在前台iOS