到现在为止(Swift 2.2)我一直很开心地使用this answer的代码 - 它很快速,它很优雅,它像梦一样工作。Swift 3:通过排序描述符排序(以前的排序)数组
extension MutableCollectionType where Index : RandomAccessIndexType, Generator.Element : AnyObject {
/// Sort `self` in-place using criteria stored in a NSSortDescriptors array
public mutating func sortInPlace(sortDescriptors theSortDescs: [NSSortDescriptor]) {
sortInPlace {
for sortDesc in theSortDescs {
switch sortDesc.compareObject($0, toObject: $1) {
case .OrderedAscending: return true
case .OrderedDescending: return false
case .OrderedSame: continue
}
}
return false
}
}
}
extension SequenceType where Generator.Element : AnyObject {
/// Return an `Array` containing the sorted elements of `source`
/// using criteria stored in a NSSortDescriptors array.
@warn_unused_result
public func sort(sortDescriptors theSortDescs: [NSSortDescriptor]) -> [Self.Generator.Element] {
return sort {
for sortDesc in theSortDescs {
switch sortDesc.compareObject($0, toObject: $1) {
case .OrderedAscending: return true
case .OrderedDescending: return false
case .OrderedSame: continue
}
}
return false
}
}
}
Swift 3改变了一切。
使用代码迁移工具和Proposal SE- 0006 - sort() => sorted(), sortInPlace() => sort()
- 尽可能
extension MutableCollection where Index : Strideable, Iterator.Element : AnyObject {
/// Sort `self` in-place using criteria stored in a NSSortDescriptors array
public mutating func sort(sortDescriptors theSortDescs: [SortDescriptor]) {
sort {
for sortDesc in theSortDescs {
switch sortDesc.compare($0, to: $1) {
case .orderedAscending: return true
case .orderedDescending: return false
case .orderedSame: continue
}
}
return false
}
}
}
extension Sequence where Iterator.Element : AnyObject {
/// Return an `Array` containing the sorted elements of `source`
/// using criteria stored in a NSSortDescriptors array.
public func sorted(sortDescriptors theSortDescs: [SortDescriptor]) -> [Self.Iterator.Element] {
return sorted {
for sortDesc in theSortDescs {
switch sortDesc.compare($0, to: $1) {
case .orderedAscending: return true
case .orderedDescending: return false
case .orderedSame: continue
}
}
return false
}
}
}
的“排序”功能编译[和工作]没有问题我已经得到了。对于'sort',我在'sort'这一行上得到一个错误:“无法将类型'(_,_) - > _'的值转换为期望的参数类型'[SortDescriptor]'”,这让我完全困惑:I不知道编译器试图在什么地方转换任何东西,因为我传递了一组SortDescriptors,它应该是一组SortDescriptors。
通常,这种类型的错误意味着你正在处理你应该有确定值的optionals,但是因为这是一个函数参数 - 并且似乎在func sorted
中没有困难 - 我可以从中读取的是那是'有问题'。到目前为止,我不知道什么是什么,因为我们处于测试的早期阶段,所以根本没有文档。
作为一种变通方法,我已经删除了排序(原排序就地)函数从我的代码,并与
舞蹈代替它让sortedArray = oldArray(分类[...] oldArray = sortedArray
但我真的很感激,如果我能得到我的排序就地功能回到
为什么不只是一些沿着'(数组作为NSArray).sortedArray(使用:sortDescriptors)''?桥接到提供您所需功能的Foundation类型没有任何问题。 – rickster
a)我宁愿避免桥接,因为有可能免费桥接在某些时候会消失。 (我们已经看到了这种趋势)。另外,b)我有一个方法可以工作,所以这不是紧急的;但我想知道这里发生了什么 - 我错过了一些东西,而我自己也看不到它。 –
你能提供一个你如何在Swift 2.2中使用这些方法的例子吗? –