注意:我找到了一种方法来完成我正在寻找的事情,代码如下。我现在需要尽可能多地优化它,因为在具有 8k 个对象的数组上执行仍然需要 20 多秒
我想对具有 path
属性并表示用户系统上的文件的对象的 Array
进行排序。我想要实现的是:
考虑这个目录结构
├── a
│ └── a.ext
├── b
│ ├── b.ext
│ ├── c.ext
│ └── d
│ └── d.ext
├── c
│ └── e.ext
├── f.ext
└── g.ext
当使用 NSFileManager 读取目录的内容时,我得到的路径顺序不是我想要的。因此,我需要对数组进行排序以获得顺序:
./f.ext
./g.ext
./a/a.ext
./b/b.ext
./b/c.ext
./b/d/d.ext
./c/e.ext
顺序应不区分大小写。对于每个文件夹,首先按字母顺序显示文件,然后显示文件夹,并且在每个文件夹中应用相同的规则。
有没有办法对数组进行排序以获得所需的顺序?排序函数是什么样的?
谢谢!
编辑:
我自己找到了一个解决方案,但我现在想知道是否可以加快速度?
func sorter(obj1: FilesListData, obj2: FilesListData) -> Bool {
var result: Bool = false
let url1 = NSURL(fileURLWithPath: obj1.path)
let url2 = NSURL(fileURLWithPath: obj2.path)
guard let c1 = url1.pathComponents else {
return result
}
guard let c2 = url2.pathComponents else {
return result
}
for i in 0..<min(c1.count, c2.count) {
if c1[i] == c2[i] {
continue
} else {
if i+1 == c1.count {
if i+1 == c2.count {
result = c1[i].lowercaseString < c2[i].lowercaseString
break
} else {
result = true
break
}
} else {
if i+1 == c2.count {
result = false
break
} else {
result = c1[i].lowercaseString < c2[i].lowercaseString
break
}
}
}
}
return asc ? result : !result //asc is a variable indicating if the order should be ascending or not
}
最佳答案
这是一个简明的方法,我认为应该足够快:
[编辑:调整以显示如何将其与对象列表一起使用]
class FileObject
{
var path:String
init(_ path:String)
{ self.path = path }
}
var files:[FileObject] =
[
FileObject("./b/c.ext"),
FileObject("./f.ext"),
FileObject("./g.ext"),
FileObject("./a/a.ext"),
FileObject("./b/b.ext"),
FileObject("./b/d/d.ext"),
FileObject("./c/e.ext")
]
files = files.map({ ($0, $0.path.rangeOfString("/", options: .BackwardsSearch)!) })
.map({ ($0, $0.path.stringByReplacingCharactersInRange($1, withString: "/ ")) })
.map({ ($0, $1.lowercaseString) })
.sort({ $0.1 < $1.1 })
.map({ $0.0 })
files.forEach({ print($0.path) })
// prints:
//
// ./f.ext
// ./g.ext
// ./a/a.ext
// ./b/b.ext
// ./b/c.ext
// ./b/d/d.ext
// ./c/e.ext
// Benchmark for 8000 gives 0.134 sec.
关于arrays - Swift:用于排序路径的排序函数(需要快!),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35758709/