Extending Array to check if it is sorted in Swift?

前端 未结 11 2401
清歌不尽
清歌不尽 2020-12-13 14:23

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

11条回答
  •  囚心锁ツ
    2020-12-13 14:47

    @kAzec's answer seems to not working when elements are equal. This is because areInIncreasingOrder(a, a) must be false according to the documentation.

    The following should work fine.

    extension Sequence {
        func isSorted(by areInIncreasingOrder: (Element, Element) throws -> Bool)
            rethrows -> Bool {
            var it = makeIterator()
            guard var previous = it.next() else { return true }
            
            while let current = it.next() {
                if try !areInIncreasingOrder(previous, current) &&
                    areInIncreasingOrder(current, previous) {
                    return false
                }
                previous = current
            }
            return true
        }
    }
    
    extension Sequence where Element: Comparable {
        func isSorted() -> Bool {
            return isSorted(by: <)
        }
    }
    

提交回复
热议问题