Extending Array to check if it is sorted in Swift?

前端 未结 11 2440
清歌不尽
清歌不尽 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条回答
  •  Happy的楠姐
    2020-12-13 15:09

    Adaptation, a solution that will work in Swift 4

    extension Array where Iterator.Element: Comparable {
        func isSorted(isOrderedBefore: (Iterator.Element, Iterator.Element) -> Bool) -> Bool  {
            for i in 1 ..< self.count {
                if isOrderedBefore(self[i], self[i-1]) {
                    return false
                }
            }
            return true
        }
    }
    

提交回复
热议问题