arrays - Swift:如何对 Array<String> 进行排序

标签 arrays swift sorting

<分区>

我有一个数组,其中包含7-4.json87-1.json102-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 接受输入的字符串并从中提取第一个和第二个数字。然后,您比较第一个数字。如果它们相等,则比较第二个数字。

关于arrays - Swift:如何对 Array<String> 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33084820/

相关文章:

c - 无法从 int 值中提取字节数组值

c - 数组的数组,具有不同的大小

ios - 在 iOS 上的 Safari 共享扩展中获取 SLComposeServiceViewController 中的 URL

python - 高效地找到对象中的最高值,并识别对象

algorithm - 长度为 N 的数组可以包含值 1,2,3 ... N^2。是否可以在 O(n) 时间内排序?

java - Apache Spark 使用 Java 从 CSV 读取数组 float

c - 数组成员的值变化不合逻辑

ios - 如何在 ios 中创建返回上一屏幕的后退按钮

ios - UitableView 下移

sorting - 在 golang 中对 slice 进行排序