Extending Array to check if it is sorted in Swift?

前端 未结 11 2434
清歌不尽
清歌不尽 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条回答
  •  -上瘾入骨i
    2020-12-13 14:57

    Actually, you can extend the Sequence protocol for a more generic solution:

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

提交回复
热议问题