我正在使用以下代碼
for(NSDictionary* key in [Tags valueForKey:@"data"]) {
if ([[key valueForKey:@"hashtag"] rangeOfString:self.searchKey options:NSCaseInsensitiveSearch].location != NSNotFound) {
NSLog(@"found key");
}
break;
}
對于字典

我不想使用 for 回圈來檢查第一個鍵值是否存在。實際上,我只想檢查字典中是否回傳了主題標簽,或者僅使用 if 陳述句。這怎么可能?
uj5u.com熱心網友回復:
您可以使用謂詞來搜索帶標簽的標簽:
// MARK: - Without Loop
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"hashtag != NULL"];
NSArray *hashtaggedTags = [tags filteredArrayUsingPredicate:predicate];
if (hashtaggedTags.count == 0) {
NSLog(@"No hashtags at all");
} else {
NSLog(@"Found some hashtags");
}
清理您的代碼以獲得最小的可行代碼:
int main(int argc, const char * argv[]) {
@autoreleasepool {
// Assuming you have some dictionary like this
NSDictionary * Tags = @{
@"data": @[ // <- Here is the array
@{ // <- here is the dictionary
@"hashtag": @"NightOut",
@"count" : @0,
}
]
};
// Getting the tag value
NSArray* tags = Tags[@"data"];
// MARK: - Without Loop
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"hashtag != NULL"];
NSArray *hashtaggedTags = [tags filteredArrayUsingPredicate:predicate];
if (hashtaggedTags.count == 0) {
NSLog(@"No hashtags at all");
} else {
NSLog(@"Found some hashtags");
}
// MARK: - With loop
// Loop through tags (not keys of the dictionary)
for (NSDictionary * tag in tags) {
// Check if `hashtag` is exists and returns something in the dictionary or not
if (tag[@"hashtag"]) {
NSLog(@"There's an object set for key @\"hashtag\"!");
} else {
NSLog(@"No object set for key @\"hashtag\"");
}
}
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/430143.html
上一篇:WPF開發隨筆收錄-DrawingVisual繪制高性能曲線圖
下一篇:在Objective-C中為UIButton使用iOS15的新ConfigurationUpdateHandler的示例
