Extending Array to check if it is sorted in Swift?

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

    The generic function, zip(), can provide a shortcut for implementation.

    extension Collection where Element: Comparable {
        var isSorted: Bool {
            guard count > 1 else {
                return true 
            }
    
            let pairs = zip(prefix(count - 1), suffix(count - 1))
    
            return !pairs.contains { previous, next in
                previous > next
            }
        }
    }
    
    [0, 1, 1, 2].isSorted  // true
    [0, 2, 2, 1].isSorted  // false
    

提交回复
热议问题