Stridable Protocol

后端 未结 1 1016
既然无缘
既然无缘 2021-01-14 17:28

I am trying to convert the following Swift 2.3 code:

//Example usage:
//(0 ..< 778).binarySearch { $0 < 145 } // 145
extension CollectionType where Ind         


        
相关标签:
1条回答
  • 2021-01-14 18:09

    In Swift 3, "Collections move their index", compare A New Model for Collections and Indices on Swift evolution. In particular, you don't call advancedBy() on an index, but an index() method on the collection to advance indices.

    So your method would be implemented in Swift 3 as

    extension RandomAccessCollection {
    
        func binarySearch(predicate: (Iterator.Element) -> Bool) -> Index {
            var low = startIndex
            var high = endIndex
            while low != high {
                let mid = index(low, offsetBy: distance(from: low, to: high)/2)
                if predicate(self[mid]) {
                    low = index(after: mid)
                } else {
                    high = mid
                }
            }
            return low
        }
    }
    

    The same method would also compile (and work) as an extension of the more general Collection type, but – as Vadim Yelagin correctly remarked, is very inefficient if the index/offset calculations cannot be done in constant time.

    0 讨论(0)
提交回复
热议问题