Extending Array to check if it is sorted in Swift?

arrays, swift

Solution

The alternative solution to a free function is to do what Swift's built-in `Array.sort` and `Array.sorted` methods do, and require that you pass a suitable comparator to the method:

extension Array {
    func isSorted(isOrderedBefore: (T, T) -> Bool) -> Bool {
        for i in 1..<self.count {
            if !isOrderedBefore(self[i-1], self[i]) {
                return false
            }
        }
        return true
    }
}

[1, 5, 3].isSorted(<) // false
[1, 5, 10].isSorted(<) // true
[3.5, 2.1, -5.4].isSorted(>) // true

Problem

I want to extend Array class so that it can know whether it is sorted (ascending) or not. I want to add a computed property called `isSorted`. How can I state the elements of the Array to be comparable? My current implementation in Playground ``` extension Array { var isSorted: Bool { for i in 1..self.count { if self[i-1] > self[i] { return false } } return true } } // The way I want to get the computed property [1, 1, 2, 3, 4, 5, 6, 7, 8].isSorted //= true [2, 1, 3, 8, 5, 6, 7, 4, 8].isSorted //= false ``` The error `Could not find an overload for '>' that accepts the supplied arguments` Of course, I still got an error because Swift doesn't know how to compare the elements. How can I implement this extension in Swift? Or am I doing something wrong here?

Original source

Related problems