Extending Array to check if it is sorted in Swift?

前端 未结 11 2454
清歌不尽
清歌不尽 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:55

    In Swift 4.2 and later you can cobble together allSatisfy and zip with some sequence slicing:

    extension Array where Element: Comparable {
        func isAscending() -> Bool {
            return zip(self, self.dropFirst()).allSatisfy(<=)
        }
    
        func isDescending() -> Bool {
            return zip(self, self.dropFirst()).allSatisfy(>=)
        }
    }
    

提交回复
热议问题