前提
字典的key或者value是数字的字符串.例如:
{"陕西省": "610000",
"河南省": "410000",
"江西省": "360000",
"海南省": "460000",
"上海市": "310000",
"吉林省": "220000",
"其他": "990000",
"安徽省": "340000",
"天津市": "120000",
"河北省": "130000",
"重庆市": "500000",
"甘肃省": "620000"}
swift
func getOrderArray(options: AnyObject?) -> [String]{
let optionType = options as! [String:String]
根据option传的是value或key进行排序
let optionTypeArray = TKOnlineTool.DictWithOption(optionType, option: .VALUE)
var IdType = [String]()
遍历字典数组,将key重新组成一个有顺序的数组
for (key , _) in optionTypeArray {
IdType.append(key)
}
return IdType
}
/**
对字典进行排序
- parameter dict: 需要排序的字典
- parameter option: 根据key或value排序
- returns: 排序后的字典数组
*/
class func DictWithOption(dict : [String : String],option : SortOption) ->[(String, String)] {
//排序后得到的字典数组
var sortResult = [(String,String)]()
switch option {
case .KEY:
sortResult = dict.sort { $0.0 < $1.0 }
case .VALUE:
sortResult = dict.sort { $0.1 < $1.1 }
}
//从排序后的数据中获取新的字典数组
return sortResult
}
OC
NSDictionary *selfCard = @{
@"陕西省": @"610000",
@"河南省": @"410000",
@"江西省": @"360000",
@"海南省": @"460000",
@"上海市": @"哈哈",
@"吉林省": @"220000",
@"其他": @"990000",
@"安徽省": @"340000",
@"天津市": @"120000",
@"河北省": @"130000",
@"重庆市": @"500000",
@"甘肃省": @"620000"};
NSArray *selfPokerKeySort = [NSArray array];
selfPokerKeySort = [selfCard keysSortedByValueUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
NSLog(@"%@----%@",obj1,obj2);
// NSComparisonResult result = [obj1 compare:obj2];
// return result == NSOrderedDescending;
int v1 = [obj1 intValue];
int v2 = [obj2 intValue];
if (v1 < v2)
return NSOrderedAscending;
else if (v1 > v2)
return NSOrderedDescending;
else
return NSOrderedSame;
}];
//排序好的key,组成的数组
NSLog(@"%@",selfPokerKeySort);