Extending Array to check if it is sorted in Swift?

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

    If you want simple function without arguments, like sort() or sorted() in Swift:

    extension Array where Element : Comparable {
        func isSorted() -> Bool {
            guard self.count > 1 else {
                return true
            }
    
            for i in 1.. self[i] {
                    return false
                }
            }
            return true
        }
    }
    

提交回复
热议问题