Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...