【问题标题】:Sort Array Alphanumerically Swift3排序数组字母数字Swift3
【发布时间】:2016-10-27 03:50:28
【问题描述】:

我有一个在 Xcode 8 Beta 中使用的函数,它先按字母顺序对数组进行排序,然后再按数字排序。

我使用的函数是:

func sortArray(arrayToSort: [String])->[String]{

let sortedArray = arrayToSort.sorted {
(first, second) in
first.compare(second, options: .numericSearch) == ComparisonResult.orderedAscending
}
   print(sortedArray)
   return sortedArray
}

但是这不再起作用了。有谁知道我如何在 Swift 3 中做到这一点?

【问题讨论】:

    标签: ios arrays sorting swift3


    【解决方案1】:

    有一个函数sort(),通过它你可以像这样对你的数组进行排序

    var arrSort = ["Rajat", "Test", "Sort", "Array","2","6"]
    arrSort.sort()
    print(arrSort)
    

    【讨论】:

      【解决方案2】:

      经过进一步挖掘,我找到了答案:

      let myArray = ["Step 6", "Step 12", "Step 10"]
      
      let sortedArray = myArray.sorted {
      $0.compare($1, options: .numeric) == .orderedAscending
      }
      
      print(sortedArray) // ["Step 6", "Step 10", "Step 12"]
      

      这是基于 Martin R 和 Duncan C 的帖子。

      谢谢! ^_______^

      【讨论】:

        【解决方案3】:

        你可以试试下面这个例子:

        func sortArray(arrayToSort: [String])->[String] {
           let sortedArray = arrayToSort.sorted(by:) {
             (first, second) in
             first.compare(second, options: .numeric) == ComparisonResult.orderedAscending
           }
           print(sortedArray)
           return sortedArray
        }
        

        【讨论】:

          猜你喜欢
          • 2017-06-05
          • 1970-01-01
          • 2023-03-31
          • 1970-01-01
          • 2021-05-03
          • 2022-01-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多