如何修复Swift Sort函数错误?

时间:2015-11-14 04:33:13

标签: swift swift2 xcode7

我有一本Swift1书,但我有Xcode 7.所以我根据Swift1书编写Swift2。我目前正在学习Swift闭包,但下面的代码会产生错误。

import Cocoa

let names = ["Chris","Alex","Ewa","Barry","Daniella"]

func backwards(s1: String, s2: String) -> Bool {
    return s1 > s2
}

print("Unsort names: \(names)")

var reversed = sort(names, backwards)
print("sort names: \(reversed)")

这是错误:

Playground execution failed: /var/folders/kt/t3wp7ckx3h1c33tfm44r4zgr0000gn/T/./lldb/1968/playground150.swift:11:16: 
error: cannot invoke 'sort' with an argument list of type '([String], (String, s2: String) -> Bool)'
var reversed = sort(names, backwards)
               ^
/var/folders/kt/t3wp7ckx3h1c33tfm44r4zgr0000gn/T/./lldb/1968/playground150.swift:11:16: 
note: overloads for 'sort' exist with these partially matching parameter lists: (inout C, (C.Generator.Element, C.Generator.Element) -> Bool), (inout [T], (T, T) -> Bool), (inout ContiguousArray<T>, (T, T) -> Bool)
var reversed = sort(names, backwards)

1 个答案:

答案 0 :(得分:0)

您必须将sort函数应用于数组对象

var reversed = names.sort(backwards)

以下是我的游乐场的截图

enter image description here