【问题标题】:Sorting array gives me error排序数组给了我错误
【发布时间】:2015-08-31 02:02:35
【问题描述】:

我有一个 arraystructs。在struct 中有两个NSDate 对象:prop1prop2。我正在尝试从最新到最旧的日期/时间对prop1 进行排序。我希望prop2 也可以根据prop1 订购。 (反之亦然。)

struct Item {
    let prop1 : NSDate
    let prop2 : NSDate
}

var myItem = [Item]()

myItem.insert(Item(prop1: myDateSecond, prop2: anotherDateSecond), atIndex: 0)
myItem.insert(Item(prop1: myDateThird, prop2: anotherDateThird), atIndex: 0)
myItem.insert(Item(prop1: myDateFirst, prop2: anotherDateFirst), atIndex: 0)

myItem.sort { $0.prop1 < $1.prop1 }

在最后一行代码,我得到以下错误:

无法使用类型为“((_, _) -> _)”的参数列表调用“排序”

我做错了什么,我该如何解决?

【问题讨论】:

  • array.sort 中的 array 是什么?
  • 我的错。我刚改成myItem.sort

标签: ios arrays swift sorting


【解决方案1】:

比较两个日期时,您必须使用 NSDate 方法compare

struct Item {
    let prop1 : NSDate
    let prop2 : NSDate
}

var myItem = [Item]()

myItem.insert(Item(prop1: myDateSecond, prop2: anotherDateSecond), atIndex: 0)
myItem.insert(Item(prop1: myDateThird, prop2: anotherDateThird), atIndex: 0)
myItem.insert(Item(prop1: myDateFirst, prop2: anotherDateFirst), atIndex: 0)

myItem.sort{$0.prop1.compare($1.prop1) == NSComparisonResult.OrderedAscending}

【讨论】:

  • 感谢您的回答!能否请您包含sort 的较长版本?这有点令人困惑且难以阅读。谢谢!
  • 这是基本的 Swift 语法。我已经发布了比较方法的文档链接。
  • 我说的是$0.prop1.compare($1.prop2)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-05
  • 1970-01-01
  • 2014-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多