2016-07-29 85 views
1

我正在嘗試對Swift中的字典數組進行排序。我的結構是這樣的:在Swift中對字符串字典進行排序

[ 
    [ 
     "DateTime": "8/16/16, 4:00 PM", 
     "Owner": "Teacher1", 
     "Subject": "AP Euro", 
     "Address": "Mr. Hughes\' Room", 
     "Type": "Final", 
     "Timestamp": "2016081616009498", 
     "Location": "On Campus", 
     "Duration": "50 min", 
     "Members": "ownerKey,1,107434,109431" 
    ], 
    [ 
     "DateTime": "7/29/16, 6:35 AM", 
     "Owner": "109431", 
     "Subject": "Algebra 2 Acc", 
     "Address": "Library", 
     "Type": "Quiz", 
     "Timestamp": "2016072906356642", 
     "Location": "On Campus", 
     "Duration": "5 min", 
     "Members": "ownerKey" 
    ] 
] 

我想在每個字典中的每個「Timestamp」價值排序的數組。我怎樣才能做到這一點?

我當前的代碼(不工作)是:

self.todayArray.sortInPlace {item1,item2 in 

    let date1 = Int("\(item1["Timestamp"])") 
    let date2 = Int("\(item2["Timestamp"])") 

    return date1 > date2 
} 
+1

你的時間戳可能是一個32位整數太大。使用'return Double(item1 [「Timestamp」]!)

回答

4

N/M以下所有的東西,它是由DateTime字段進行排序,你要排序的時間戳字段這已經是字典序排序,所以只需使用:

foo.sortInPlace { $0["Timestamp"] < $1["Timestamp"] } 

由於時間戳是一個字符串編碼的日期,你需要將其轉換爲第一的東西更實用,使用NSDateFormatter是最簡單的方法:

有一個在這裏有很多的!,你應該做更合適的東西,但是這給你的基本思路:

let foo = [ 
    [ 
     "DateTime": "8/16/16, 4:00 PM", 
     "Owner": "Teacher1", 
     "Subject": "AP Euro", 
     "Address": "Mr. Hughes\' Room", 
     "Type": "Final", 
     "Timestamp": "2016081616009498", 
     "Location": "On Campus", 
     "Duration": "50 min", 
     "Members": "ownerKey,1,107434,109431" 
    ], 
    [ 
     "DateTime": "7/29/16, 6:35 AM", 
     "Owner": "109431", 
     "Subject": "Algebra 2 Acc", 
     "Address": "Library", 
     "Type": "Quiz", 
     "Timestamp": "2016072906356642", 
     "Location": "On Campus", 
     "Duration": "5 min", 
     "Members": "ownerKey" 
    ] 
] 

let formatter = NSDateFormatter() 
formatter.dateFormat = "M/dd/yy, h:mm a" 

let sorted = foo.sort { 
    formatter.dateFromString($0["DateTime"]!)!.compare(formatter.dateFromString($1["DateTime"]!)!) != .OrderedDescending 
} 
print("\(sorted)") 
+0

foo.sort {$ 0 [「Timestamp」] <$ 1 [「Timestamp」]}是foo.sortInPlace {$ 0 [「Timestamp」] <$ 1 [「Timestamp」]}? –

+0

取決於你想要什麼。爲了模仿你的原始代碼,是的,sortInPlace是合適的。我只是儘量避免在大部分時間使用它。 –

相關問題