我有一个结构数组,我希望能够使用sort()中的任何一个对它进行排序(如果可能)
struct{
var deadline = 0
var priority = 0
}
我在Swift编程语言的文档中查看了sort(),但它只显示了简单的数组。可以使用sort()还是我必须建立自己的?
答案 0 :(得分:35)
下面的排序函数完全相同,唯一的区别是它们有多短和富有表现力:
完整声明:
myArr.sort { (lhs: EntryStruct, rhs: EntryStruct) -> Bool in
// you can have additional code here
return lhs.deadline < rhs.deadline
}
缩短封闭声明:
myArr.sort { (lhs:EntryStruct, rhs:EntryStruct) in
return lhs.deadline < rhs.deadline
}
// ... or even:
myArr.sort { (lhs, rhs) in return lhs.deadline < rhs.deadline }
紧凑的闭包声明:
myArr.sort { $0.deadline < $1.deadline }
完整声明:
let newArr = myArr.sorted { (lhs: EntryStruct, rhs: EntryStruct) -> Bool in
// you can have additional code here
return lhs.deadline < rhs.deadline
}
缩短封闭声明:
let newArr = myArr.sorted { (lhs:EntryStruct, rhs:EntryStruct) in
return lhs.deadline < rhs.deadline
}
// ... or even:
let newArr = myArr.sorted { (lhs, rhs) in return lhs.deadline < rhs.deadline }
紧凑的闭包声明:
let newArr = myArr.sorted { $0.deadline < $1.deadline }