swift - 单击按钮在升序和降序之间交替排序

标签 swift

我想用我的 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/

相关文章:

ios - 在 swift 模型中保存 json 数据的最佳方法是什么

ios - Swift 中可拖动的 UIButton/元素?

swift - 我可以使用 Couchbase Lite 在 'map' 闭包中查询数据库吗?

xcode - Spritekit 分数 self 倍增

ios - 如何将 Parse SDK 与 Xcode 7 和 iOS 9 结合使用

swift - 在继续功能之前等待图像上传 - Swift 5 Firebase Storage

swift - 旋转后标签栏不恢复原尺寸

swift - 在 Swift 中对 TableView 的 plist 数组进行排序

ios - 使用 Alamofire 请求获取图像数据

swift - FBSDKApplicationDelegate 申请openURL :sourceApplication:annotation deprecated