我有一个数组
,其中包含7-4.json
、87-1.json
和102-4 等值。 json
并想对其进行排序(升序)。我使用了以下代码:
var fileNames = ["7-4.json", "87-1.json", "102-4.json"]
fileNames = fileNames.sort{ $0 < $1 }
print(fileNames)
结果是:
["102-4.json", "7-4.json", "87-1.json"]
所以它没有像我看的那样起作用。如何将其排序为 7-4、87-1、102-4?
给你:
var fileNames = ["7-4.json", "87-1.json", "102-4.json"]
func sortWithCustomFormat(first: String, second: String) -> Bool{
func extract(value: String) -> (Int, Int){
return (Int(value.componentsSeparatedByString("-").first!)!, Int(value.componentsSeparatedByString("-").last!.componentsSeparatedByString(".").first!)!)
}
let firstNumber = extract(first)
let secondNumber = extract(second)
if firstNumber.0 != secondNumber.0 { return firstNumber.0 < secondNumber.0 }
return firstNumber.1 < secondNumber.1
}
fileNames.sort(sortWithCustomFormat)
函数 sortWithCustomFormat
有一个函数 extract
接受输入的字符串并从中提取第一个和第二个数字。然后,您比较第一个数字。如果它们相等,则比较第二个数字。