I have an array of a struct and I would like to be able to sort it by either of the two variables using sort() if possible
我有一个结构体数组,如果可能的话,我希望能够使用sort()对它进行排序
struct{
var deadline = 0
var priority = 0
}
I looked at sort() in the documentation for the Swift programming language but it shows only simple arrays. can sort() be used or will I have to build my own?
我在Swift编程语言的文档中查看了sort(),但它只显示了简单的数组。我可以使用sort()或者我必须自己构建吗?
1 个解决方案
#1
26
Sort within the same array variable
Sort functions bellow are exactly the same, the only difference how short and expressive they are:
排序函数bellow是完全相同的,唯一的区别是它们的简短和表达性:
Full declaration:
全面声明:
myArr.sort { (lhs: EntryStruct, rhs: EntryStruct) -> Bool in
// you can have additional code here
return lhs.deadline < rhs.deadline
}
Shortened closure declaration:
缩短关闭声明:
myArr.sort { (lhs:EntryStruct, rhs:EntryStruct) in
return lhs.deadline < rhs.deadline
}
// ... or even:
myArr.sort { (lhs, rhs) in return lhs.deadline < rhs.deadline }
Compact closure declaration:
紧凑的闭包声明:
myArr.sort { $0.deadline < $1.deadline }
Sort to a new array variable
Full declaration:
全面声明:
let newArr = myArr.sorted { (lhs: EntryStruct, rhs: EntryStruct) -> Bool in
// you can have additional code here
return lhs.deadline < rhs.deadline
}
Shortened closure declaration:
缩短关闭声明:
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 }
Compact closure declaration:
紧凑的闭包声明:
let newArr = myArr.sorted { $0.deadline < $1.deadline }
#1
26
Sort within the same array variable
Sort functions bellow are exactly the same, the only difference how short and expressive they are:
排序函数bellow是完全相同的,唯一的区别是它们的简短和表达性:
Full declaration:
全面声明:
myArr.sort { (lhs: EntryStruct, rhs: EntryStruct) -> Bool in
// you can have additional code here
return lhs.deadline < rhs.deadline
}
Shortened closure declaration:
缩短关闭声明:
myArr.sort { (lhs:EntryStruct, rhs:EntryStruct) in
return lhs.deadline < rhs.deadline
}
// ... or even:
myArr.sort { (lhs, rhs) in return lhs.deadline < rhs.deadline }
Compact closure declaration:
紧凑的闭包声明:
myArr.sort { $0.deadline < $1.deadline }
Sort to a new array variable
Full declaration:
全面声明:
let newArr = myArr.sorted { (lhs: EntryStruct, rhs: EntryStruct) -> Bool in
// you can have additional code here
return lhs.deadline < rhs.deadline
}
Shortened closure declaration:
缩短关闭声明:
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 }
Compact closure declaration:
紧凑的闭包声明:
let newArr = myArr.sorted { $0.deadline < $1.deadline }