Swift - 使用多种对象类型排序,多维数组,可变顺序



我正在尝试对包含字符串,日期和其他数字的多个记录的数组进行排序。 我希望能够根据第 1、2、3 和 4 个选项使用升序/降序选项对最多 4 列进行排序。基于其他示例,我能够实现此目标,但仅用于作为字符串排序。

代码将对字符串数组进行排序,但由于某些字符串是数字和日期,因此排序不符合预期。 我想使用 .localizedStandardComare 方法进行排序,但我不知道如何将其合并到数组的此代码中。

import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
var array = [["a","e","def","ttt","",""],["z","2019/5/28","ccc","123",""], ["z","2019/10/23","def","567",""]]
// Constants below are assigned based on optional ascending/descending choice
let a1 = 4  // dummy column
let a2 = 0  // descending order for column 0
let b1 = 1  // ascending order for column 1
let b2 = 4  // dummy column
let sorted = array.sorted(by: {($0[a1],$1[a2],$0[b1],$1[b2]) < ($1[a1],$0[a2],$1[b1],$0[b2])})
print("sorted array=", sorted)
// The results below show that columns 0 and 1 are sorted correctly as strings, but column 1 needs to be sorted as date similar to what this closure would achieve for a simpler array
// --> {$0.localizedStandardCompare($1) == orderedAscending}
sorted array= [["z", "2019/10/23", "def", "567", ""], ["z", "2019/5/28", "ccc", "123", ""], ["a", "e", "def", "ttt", "", ""]]

下面使用结构数组编写的新工作代码。 更多的代码,但我怀疑可以更有效地编写:

var array = [["asdf","45","10/3/2019","100.34",""],["asdf","100","6/12/2019","12.3",""],["asdf","10","12/16/2019","5.67",""],["asdf2","450","4/3/2019","923",""],["asdf3","9","5/20/2019","567",""]]
struct arrayStruct {
var stringV : String!
var intV : Int!
var dateV : Date!
var costV : Float!
var stringD : String!
}
var newArray = [arrayStruct]()
let dateFormatter = DateFormatter()
for i in 0 ..< array.count {
let rowArray = array[i]
let rowInt = Int(rowArray[1])
let rowDate = dateFormatter.date(from: rowArray[2])
let rowCost = Float(rowArray[3])
newArray.append(arrayStruct(stringV: rowArray[0], intV: rowInt!, dateV: rowDate!, costV: rowCost!, stringD: rowArray[4]))
}
newArray.sort(by: {($0.stringV, $0.dateV) < ($1.stringV, $1.dateV)})
print("New Sorted Array:")
for i in 0 ..< newArray.count {
print("col0=",newArray[i].stringV!, " col2=",newArray[i].dateV!)
}
Result: 
New Sorted Array:
col0= asdf  col2= 2019-06-12 04:00:00 +0000
col0= asdf  col2= 2019-10-03 04:00:00 +0000
col0= asdf  col2= 2019-12-16 05:00:00 +0000
col0= asdf2  col2= 2019-04-03 04:00:00 +0000
col0= asdf3  col2= 2019-05-20 04:00:00 +0000

最新更新