本文介绍了排序根据一个元组的第二值的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢阅读我的文章。

我有元组的数组声明如:

I have an array of tuples declared as such:

VAR myArray的:[(ITEM1:字符串?ITEM2:NSDate的)] = []

目前我想我的排序基于每一个元组的项目2,其类型是的NSDate?

At the end of my loop I want to sort my array of tuples based on every tuple's item2, whose type is NSDate?.

在此基础上answer和我尝试以下,但收到此编译器错误,不能调用'排序'类型的参数列表'((_,_) - GT; _)。

Based on this answer and this answer I tried the following, but received this compiler error, "cannot invoke 'sort' with an argument list of type '((_,_) -> _)'.

下面是我的尝试:

myArray.sort {$0.1.item2?.compare($1.1.item2?) == NSComparisonResult.OrderedDescending }

P.S。 的println()工作正常,并打印ITEM1和ITEM2作为可选。

P.S. println() works fine and prints item1 and item2 as an optional.

推荐答案

您必须实现可比协议的NSDate

You must implement Comparable protocol to NSDate

public func ==(lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs === rhs || lhs.compare(rhs) == .OrderedSame
}

public func <(lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs.compare(rhs) == .OrderedAscending
}

extension NSDate: Comparable { }

这之后,您可以按日期的元组进行排序:

After that you can sort your tuples by date:

myArray!.sort {$0.1 == $1.1 ? $0.1 > $1.1 : $0.1 > $1.1 }

这篇关于排序根据一个元组的第二值的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 10:51