用最后一个对象在Swift中排序数组

时间:2015-10-18 01:50:24

标签: arrays swift sorting

我有一个看起来像这样的数组

[[AAA,BBB,CCC,3],
 [DDD,EEE,FFF,1],
 [GGG,HHH,III,2]]

我使用以下Objective C代码按每个字符串组件中的最后一个值对数组进行排序:

NSSortDescriptor *aSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"@lastObject"                                                                           ascending:YES                                                                            comparator:^(id obj1, id obj2) {
                if ([obj1 integerValue] > [obj2 integerValue]) {
                    return (NSComparisonResult)NSOrderedDescending;
                }
                if ([obj1 integerValue] < [obj2 integerValue]) {
                    return (NSComparisonResult)NSOrderedAscending;
                }
                return (NSComparisonResult)NSOrderedSame;
            }];

listNavData = [NSMutableArray arrayWithArray:[listNavDataUnsorted sortedArrayUsingDescriptors:[NSArray arrayWithObject:aSortDescriptor]]];

我如何在Swift中执行此操作?我试图将代码转换为Swift但失败了。有没有一种很好的方法在Swift中根据数组组件中的最后一个组件对数组进行排序,以便我有以下内容?

 [[DDD,EEE,FFF,1],
  [GGG,HHH,III,2],
  [AAA,BBB,CCC,3]]

2 个答案:

答案 0 :(得分:3)

我不确定我完全理解你的&#34; listNavDataUnsorted&#34;的结构。数组,但以下Swift代码重复了您使用Objective-C代码实现的功能。

let listNavDataUnsorted: NSArray = [
    ["AAA", "BBB", "CCC", 3],
    ["DDD", "EEE", "FFF", 1],
    ["GGG", "HHH", "III", 2]
]

func compare(obj1: AnyObject, obj2: AnyObject) -> NSComparisonResult {
    if Int(obj1 as! NSNumber) > Int(obj2 as! NSNumber) {
        return NSComparisonResult.OrderedDescending
    }
    else if Int(obj1 as! NSNumber) < Int(obj2 as! NSNumber) {
        return NSComparisonResult.OrderedAscending
    }
    else {
        return NSComparisonResult.OrderedSame
    }
}

let sortDescriptor = NSSortDescriptor(key: "@lastObject", ascending: true, comparator: compare)   
let listNavDataSorted = listNavDataUnsorted.sortedArrayUsingDescriptors([sortDescriptor])

我怀疑使用内置阵列sort(_:)在Swift中实现这一目标的更好方法,但我还没有想到这一点。我还没有想出在compare调用中简单地包含NSSortDescriptor()函数的语法,尽管在Swift中这绝对是可能的。

答案 1 :(得分:2)

在解释问题的基础上建立@ MattLewin的侦探工作,这是使用Array sort()方法的Swift版本:

let listNavDataUnsorted = [
    ["AAA", "BBB", "CCC", 3],
    ["DDD", "EEE", "FFF", 1],
    ["GGG", "HHH", "III", 2]
]

let listNavDataSorted = listNavDataUnsorted.sort {($0.last as? Int) < ($1.last as? Int)}

print(listNavDataSorted) // [[DDD, EEE, FFF, 1], [GGG, HHH, III, 2], [AAA, BBB, CCC, 3]]

如果您的最后一项是String,并且您希望按其整数值排序:

let listNavDataUnsorted = [
    ["AAA", "BBB", "CCC", "3"],
    ["DDD", "EEE", "FFF", "111"],
    ["GGG", "HHH", "III", "22"]
]

let listNavDataSorted = listNavDataUnsorted.sort {Int($0.last ?? "") < Int($1.last ?? "")}

print(listNavDataSorted) // [["AAA", "BBB", "CCC", "3"], ["GGG", "HHH", "III", "22"], ["DDD", "EEE", "FFF", "111"]]