Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

ios - SWIFT 2 - Sort Multi dimensional array by date

I am trying to sort my array by date, I have been trying almost everything but with no results.

This is the closer I got but I get a waring:

Constant 'sortedDate' inferred to have type ()

var Names = [[String]]()

 Names = [
            ["aaa", "bob", "ccc", "26-10-2015 17:50"],
            ["aaa-1", "bbb-1", "ccc-1", "22-10-2015 11:20"],
            ["aaa-2", "bbb-2", "bbb-2", "01-03-2015 17:00"]
        ]

let sortedDate = Names.sortInPlace({ return $0[3].compare($1[3]) == NSComparisonResult.OrderedAscending })

        print("(sortedDate)")
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your data is String, not date. Use an NSDateFormatter to convert it to NSDate:

let names = [
    ["aaa", "bob", "ccc", "26-10-2015 17:50"],
    ["aaa-1", "bbb-1", "ccc-1", "22-10-2015 11:20"],
    ["aaa-2", "bbb-2", "bbb-2", "01-03-2015 17:00"]
]

let formatter = NSDateFormatter()
formatter.dateFormat = "dd-MM-yyyy HH:mm"

let sortedDate = names.sort {
    let date1 = formatter.dateFromString($0[3])
    let date2 = formatter.dateFromString($1[3])
    return date1?.timeIntervalSince1970 < date2?.timeIntervalSince1970
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...