Extending Array to check if it is sorted in Swift?

前端 未结 11 2433
清歌不尽
清歌不尽 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 15:07

    In Swift 2.0 you can now extend protocols!

    extension CollectionType where Generator.Element: Comparable {
    
        public var isSorted: Bool {
    
            var previousIndex = startIndex
            var currentIndex = startIndex.successor()
    
            while currentIndex != endIndex {
    
                if self[previousIndex] > self[currentIndex] {
                    return false
                }
    
                previousIndex = currentIndex
                currentIndex = currentIndex.successor()
            }
    
            return true
        }
    
    }
    
    [1, 2, 3, 4].isSorted // true
    ["a", "b", "c", "e"].isSorted // true
    ["b", "a", "c", "e"].isSorted // false
    [/* Anything not implementing `Comparable` */].isSorted // <~~ Type-error
    

    Note that because we're using Indexable.Index instead of a simple Int as an index we have to use a while-loop instead, which looks a bit less pretty and clear.

提交回复
热议问题