【问题标题】:Use sort for multidimensional array (array in array) in Swift?在 Swift 中对多维数组(数组中的数组)使用排序?
【发布时间】:2023-03-18 07:05:01
【问题描述】:

我想知道如何在 Swift 中使用sortsorted 函数处理多维数组?

例如他们的数组:

[
    [5, "test888"],
    [3, "test663"],
    [2, "test443"],
    [1, "test123"]
]

我想按照第一个 ID 从低到高排序:

[
    [1, "test123"],
    [2, "test443"],
    [3, "test663"],
    [5, "test888"]
]

那么我们该怎么做呢?谢谢!

【问题讨论】:

    标签: arrays swift sorting multidimensional-array


    【解决方案1】:

    你可以使用sort:

    let sortedArray = arr.sort { ($0[0] as? Int) < ($1[0] as? Int) }
    

    结果:

    [[1, test123], [2, test443], [3, test663], [5, test123]]

    我们可以选择将参数转换为 Int,因为您的数组的内容是 AnyObject。

    注意:sort 之前在 Swift 1 中被命名为 sorted


    如果将内部数组声明为 AnyObject 没问题,空的不会被推断为 NSArray:

    var arr = [[AnyObject]]()
    
    let sortedArray1 = arr.sort { ($0[0] as? Int) < ($1[0] as? Int) }
    
    print(sortedArray1) // []
    
    arr = [[5, "test123"], [2, "test443"], [3, "test663"], [1, "test123"]]
    
    let sortedArray2 = arr.sort { ($0[0] as? Int) < ($1[0] as? Int) }
    
    print(sortedArray2)  // [[1, test123], [2, test443], [3, test663], [5, test123]]
    

    【讨论】:

    • 小心,这在 Swift 3 中再次发生了变化,其中sort 是变异方法,sorted 是返回新数组的方法...
    【解决方案2】:

    我认为你应该使用一个元组数组,那么类型转换就不会有任何问题:

    let array : [(Int, String)] = [
        (5, "test123"),
        (2, "test443"),
        (3, "test663"),
        (1, "test123")
    ]
    
    let sortedArray = array.sorted { $0.0 < $1.0 }
    

    Swift 是关于类型安全的

    (如果您使用的是 Swift 2.0,请将 sorted 更改为 sort

    【讨论】:

    • 好的,这段代码运行良好。而且我还想问一下,我们如何使用 sorted 对 NSDate 进行排序(从现在到过去)? :)
    【解决方案3】:

    Swift 5.0 更新

    排序函数被重命名为排序。这是新语法

    let sortedArray = array.sorted(by: {$0[0] < $1[0] })
    

    例子,

    let array : [(Int, String)] = [
        (5, "test123"),
        (2, "test443"),
        (3, "test663"),
        (1, "test123")
    ]
    
    let sorted = array.sorted(by: {$0.0 < $1.0})
    print(sorted)
    print(array)
    
    
    Output:
    [(1, "test123"), (2, "test443"), (3, "test663"), (5, "test123")]
    
    [(5, "test123"), (2, "test443"), (3, "test663"), (1, "test123")]
    

    【讨论】:

      【解决方案4】:

      在 Swift 3,4 中,您应该使用“比较”。例如:

      let sortedArray.sort { (($0[0]).compare($1[0]))! == .orderedDescending }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-10-06
        • 2012-09-04
        • 2019-11-26
        • 2018-07-11
        • 2012-06-10
        • 2021-10-12
        • 2017-01-26
        相关资源
        最近更新 更多