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
262 views
in Technique[技术] by (71.8m points)

ios - How do you compare 2 operands of type Date? to sort an array in Swift?

In order to sort an array of a custom struct that has bools, integers, and dates. I successfully used the syntax below for a boolean value and it works for the "bride" and "groom" cases. When I attempted to add a sort for 2 Date variables though, I got the error error that:

"Binary operator '>' cannot be applied to two 'Date?' operands"

I was under the impression that Date values could get compared in a similar fashion with normal > < == criteria, but I presume I am getting the error because the values are not unwrapped? If that is correct , I don't think I can do an if let to turn Date? into an unwrapped Date, so I am not sure how I can compare these values.

    var sortedImages = [submitted_image]()
    switch sortOption {
    case .brideInPic:
        print("bride")
        sortedImages = Images.sorted(by: {$0.brideInPic && !$1.brideInPic})
        print("sortedImages: (sortedImages.count), Images: (Images.count)")
    case .groomInPic:
        print("groom")
        sortedImages = Images.sorted(by: {$0.groomInPic && !$1.groomInPic})
        print("sortedImages: (sortedImages.count), Images: (Images.count)")
    case .create_dt:
        print("create")
        sortedImages = Images.sorted(by: {$0.create_dt > $1.create_dt})
    }
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Optionals cannot be compared directly (compare SE-0121 – Remove Optional Comparison Operators). But you can use the nil-coalescing operator ?? to provide a default date for entries without creation date:

Images.sorted(by: {$0.create_dt ?? .distantPast > $1.create_dt ?? .distantPast })

With .distantPast the entries without creation date are sorted to the end of the list. With .distantFuture they would be sorted to the start of the list.


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

...