Extending Array to check if it is sorted in Swift?

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

    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..) // true
    

提交回复
热议问题