Tuesday, September 1, 2020

Sorting in Swift

 If you have even tried to sort objects, you might have noticed it was a pain.

If you have a Date object:

struct Date {

    let year: Int

    let month: Int

    let day: Int

}

Then comparing two dates would be:

    static func < (lhs: Date, rhs: Date) -> Bool {

        if lhs.year != rhs.year {

            return lhs.year < rhs.year

        } else if lhs.month != rhs.month {

            return lhs.month < rhs.month

        } else {

            return lhs.day < rhs.day

        }

                    } 

Except if you use tuples and then it becomes:

    static func < (lhs: Date, rhs: Date) -> Bool {

        return (lhs.year, lhs.month, lhs.day) 

                < (rhs.year, rhs.month, rhs.day)

    }


(example is taken from Comparable documentation at Apple) 

No comments:

Post a Comment