我有一些字符串和整数混合的数据,
"003G"
"002P"
"001P"
"018P"
"002G"
"019P"
"001G"
"020P"
"012P"
"011P"
"012G"
"013P"
"007P"
"011G"
"010P"
"009P"
"008P"
"005P"
"006P"
"014P"
"007G"
"010G"
"009G"
"008G"
"015P"
"006G"
"005Ga"
"004P"
"016P"
"005G"
"004G"
"003P"
"017P"
需要像这样的输出:
"001P"
"002P"
"003P"
"004P"
"005P"
"006P"
"007P"
"008P"
"009P"
"010P"
"011P"
"012P"
"013P"
"014P"
"015P"
"016P"
"017P"
"018P"
"019P"
"020P"
"001G"
"002G"
"003G"
"004G"
"005G"
"005Ga"
"006G"
"007G"
"008G"
"009G"
"010G"
"011G"
"012G"
同时Android使用
*[0-9,0P-9P,0G-9G]
进行了排序
最佳答案
这是一个非常不寻常的排序顺序。您必须使用Comparator
编写自定义描述符
需要两个描述符。
let sortDescriptor1 = NSSortDescriptor(key: "referenceNo", ascending: false) { (obj1, obj2) -> ComparisonResult in
let string1 = obj1 as! String
let string2 = obj2 as! String
let fourthChar1 = string1.index(string1.startIndex, offsetBy: 3)
let fourthChar2 = string2.index(string2.startIndex, offsetBy: 3)
return String(string1[fourthChar1]).compare(String(string2[fourthChar2]))
}
numeric
选项对前3个字符进行升序排序,并考虑xxxxa
的大小写let sortDescriptor2 = NSSortDescriptor(key: "referenceNo", ascending: true) { (obj1, obj2) -> ComparisonResult in
let string1 = obj1 as! String
let string2 = obj2 as! String
let fourthChar1 = string1.index(string1.startIndex, offsetBy: 3)
let fourthChar2 = string2.index(string2.startIndex, offsetBy: 3)
let orderedResult = string1.substring(to: fourthChar1).compare(string2.substring(to: fourthChar2), options: .numeric)
if orderedResult == .orderedSame {
return string1.characters.count < string2.characters.count ? .orderedAscending : .orderedDescending
} else {
return orderedResult
}
}
当然,这假定值是在ASCII范围内始终为4个字符或更多的字符串。
关于ios - 排序核心数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44694471/