2016-04-18 86 views
1

我想诉诸我的桌子。 我有此代码部分:在按钮上按升序和降序进行排序之间交替点击

func ReSort() { 
    CoreDataItems.sortInPlace({$0.RowName< $1.RowName}) 
    tableView.reloadData() 
} 

此功能将在按下按钮后调用。 但我怎么能解决这个问题,如果我按下按钮,在第一时间里,排序函数会像这样排序是:

$0.RowName < $1.RowName 

和第二次是这样的:

$0.RowName > $1.RowName 

和等等。

回答

1

您需要将排序的当前状态存储在实例变量中,例如,现在

var sortAscending : Bool = true 

,你可以这样做:

func ReSort() { 
    CoreDataItems.sortInPlace({sortAscending ? $0.RowName < $1.RowName : $0.RowName > $1.RowName}) 
    sortAscending = !sortAscending 
    tableView.reloadData() 
} 

sortAscending值将>和比较<之间进行选择。在排序之后完成的赋值

sortAscending = !sortAscending 

truefalse之间交替。

具有相同效果的较短,但略小于可读代码使用==操作者作为替换为倒置XORBool值:

func ReSort() { 
    CoreDataItems.sortInPlace({sortAscending == ($0.RowName < $1.RowName) }) 
    sortAscending = !sortAscending 
    tableView.reloadData() 
} 
+0

感谢,这工作正常:)是有使用可变insteads的方式的RowName常量? – Stack108

+0

@ Stack108欢迎您!我看到你的[其他问题](http://stackoverflow.com/q/36710670/335858),所以我假设你知道答案。 – dasblinkenlight