How to compare two dictionary key values and print text in cell in iOS?

做~自己de王妃 提交于 2020-01-06 18:30:33

问题


I have two dictionary with multiple items. I want to compare values.

Dict1:{
"Displacement_trim" = "49.26 ";
"Dry_Weight" = "<null>";
}

Dict2:{
"Displacement_trim" = "171.20 ";
"Dry_Weight" = "<null>";
} 
  1. I want to know which "Displacement_trim" is greater.
  2. Also checking null values.
  3. Print the data in cell.

How can I achieve this?


回答1:


To find out which value from the dict is bigger use the following code:

Swift 3

let dict1 = [ "Displacement_trim" : "49.26", "Dry_Weight" : "<null>" ]
let dict2 = [ "Displacement_trim" : "171.20", "Dry_Weight" : "<null>" ]

// I force unwrapped everything for brevity
if Float(dict1["Displacement_trim"]!)! > Float(dict2["Displacement_trim"]!)! {
    // highlight label for dict1
} else {
    // highlight label for dict2
}

Objective-C

NSDictionary *dict1 = @{@"Displacement_trim" : @"49.26", @"Dry_Weight" : @"<null>"};
NSDictionary *dict2 = @{@"Displacement_trim" : @"171.20", @"Dry_Weight" : @"<null>"};

NSString *dict1DisplacementTrim = dict1[@"Displacement_trim"];
NSString *dict2DisplacementTrim = dict2[@"Displacement_trim"];

if (dict1DisplacementTrim.floatValue > dict2DisplacementTrim.floatValue) {
    // highlight label for dict1
} else {
    // highlight label for dict2
}



回答2:


NSMutableDictionary *dict1,*dict2;

 dict1 = [[NSMutableDictionary alloc]init];
dict2 = [[NSMutableDictionary alloc]init];

[dict1 setObject:[NSNumber numberWithFloat:13.20] forKey:@"Displacement_trim"];

[dict2 setObject:[NSNumber numberWithFloat:10.20] forKey:@"Displacement_trim"];

if ( [[dict1 valueForKey:@"Displacement_trim"] compare:[dict2 valueForKey:@"Displacement_trim"]]==NSOrderedAscending) {
    NSLog(@"dict 2 is greater");
}else{
    NSLog(@"dict 1 is greater");
}

Let me know if any thing get wrong.



来源:https://stackoverflow.com/questions/40506474/how-to-compare-two-dictionary-key-values-and-print-text-in-cell-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!