Extending Array to check if it is sorted in Swift?

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

    The most flexible solution to me is a combination of NSAddict's and Wes Campaigne's answer. I.e. combine the advantage of being able to extend protocols and to pass comparator functions as arguments. This eliminates the restrictions both to use it only with arrays and to constrain it to elements conforming to Comparable protocol.

    extension CollectionType
    {
        func isSorted(isOrderedBefore: (Generator.Element, Generator.Element) -> Bool) -> Bool
        {
            var previousIndex = startIndex
            var currentIndex = startIndex.successor()
    
            while currentIndex != endIndex
            {
                if isOrderedBefore(self[previousIndex], self[currentIndex]) == false
                {
                    return false
                }
    
                previousIndex = currentIndex
                currentIndex = currentIndex.successor()
            }
    
            return true
        }
    }
    

    This can be used on any Collection type and sorting criteria can be defined according to your needs.

提交回复
热议问题