我想用我的 table 。 我有这段代码:
func ReSort() {
CoreDataItems.sortInPlace({$0.RowName< $1.RowName})
tableView.reloadData()
}
此函数将在按下按钮后调用。 但我该如何解决这个问题,如果我第一次按下按钮,排序功能将按如下方式排序:
$0.RowName < $1.RowName
第二次是这样的:
$0.RowName > $1.RowName
等等。
最佳答案
您需要将排序的当前状态存储在一个实例变量中,例如
var sortAscending : Bool = true
现在你可以这样做了:
func ReSort() {
CoreDataItems.sortInPlace({sortAscending ? $0.RowName < $1.RowName : $0.RowName > $1.RowName})
sortAscending = !sortAscending
tableView.reloadData()
}
sortAscending
的值将在 >
之间选择和 <
在比较中。作业
sortAscending = !sortAscending
排序完成后会在 true
之间交替和 false
.
具有相同效果的更短但可读性稍差的代码使用 ==
运算符作为倒置 XOR
的替代品在 Bool
值(value)观:
func ReSort() {
CoreDataItems.sortInPlace({sortAscending == ($0.RowName < $1.RowName) })
sortAscending = !sortAscending
tableView.reloadData()
}
关于swift - 单击按钮在升序和降序之间交替排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36703547/