【问题标题】:Swift 3.0 sort - Argument passed to call that takes no argumentsSwift 3.0 sort - 传递给不带参数的调用的参数
【发布时间】:2018-03-15 15:15:38
【问题描述】:

我目前正在尝试将一些 Swift 2 代码移植到 Swift 3.0。

这里有一行代码让我抓狂。

    public private(set) var searchHistory: [SearchHistoryEntry] = [SearchHistoryEntry]() // Struct that is cComparable 
....
...
    searchHistory.sortInPlace({ $0.lastUsage.isAfter($1.lastUsage) })

这是我的 Swift 3.0 版本

searchHistory.sort(by:{ $0.lastUsage.isAfter($1.lastUsage) })

lastUsage 的类型为 Date

编译器抱怨以下错误消息

参数传递给不带参数的调用

任何想法我做错了什么? 我真的不明白编译器想要告诉什么。 排序需要一个块,我通过它,一切都应该没问题。

更新

我发现了错误。 Swift 将所有 NSDate 属性转换为 Date,我们在 NSDate 上得到了一个名为 isAfter 的扩展。所以编译器再也找不到 isAfter 了。编译器错误消息完全具有误导性。

【问题讨论】:

  • searchHistorylastUsage 有哪些类型?您能否为您的代码行提供更多上下文?
  • 对不起,我可以做到。
  • 我得到了那个错误.. Swift 将所有 NSDate 属性转换为 Date。我们在 NSDate 上得到了一个名为 isAfter 的扩展。所以编译器再也找不到 isAfter 了。编译器错误消息完全具有误导性。
  • 这不是 swift 编译器第一次给出神秘的错误信息 :)
  • 不过,谢谢;)

标签: swift swift3


【解决方案1】:

我会使用sorted(by: ),即

searchHistory.sorted(by: {$0.lastUsage > $1.lastUsage})

完整的工作示例:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"

struct ExerciseEquipment
{
    let name: String
    let lastUsage: Date
}

let myExerciseEquipment =
[
    ExerciseEquipment(name: "Golf Clubs", lastUsage: dateFormatter.date(from: "03-16-2015")!),
    ExerciseEquipment(name: "Tennis Racket", lastUsage: dateFormatter.date(from: "06-30-2003")!),
    ExerciseEquipment(name: "Skis", lastUsage: dateFormatter.date(from: "02-08-2017")!),
    ExerciseEquipment(name: "Hockey Stick", lastUsage: dateFormatter.date(from: "09-21-2010")!),
    ExerciseEquipment(name: "Mountain Bike", lastUsage: dateFormatter.date(from: "10-30-2016")!)
]

print(myExerciseEquipment.sorted(by: {$0.lastUsage > $1.lastUsage}))

...结果

[ExerciseEquipment(名称:“滑雪”,lastUsage:2017-02-08 05:00:00 +0000),ExerciseEquipment(名称:“山地自行车”,lastUsage:2016-10-30 04:00:00 +0000),ExerciseEquipment(名称:“高尔夫俱乐部”,lastUsage: 2015-03-16 04:00:00 +0000),运动器材(名称:“曲棍球棒”, lastUsage: 2010-09-21 04:00:00 +0000),ExerciseEquipment(名称:“网球 Racket", lastUsage: 2003-06-30 04:00:00 +0000)]

【讨论】:

    【解决方案2】:

    刚刚遇到同样的错误。我之前在 Swift 中的代码是:

    let sorted =  array.sorted {
        $0.characters.count < $1.characters.count
    }
    

    但是,它不再起作用了。看起来他们已经用 sorted(by: ) 的参数更新了 sorted()

    以下内容现在对我有用:

    let sorted = array.sorted(by: {x, y -> Bool in 
        x.characters.count < y.characters.count 
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-05
      • 1970-01-01
      • 1970-01-01
      • 2021-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多