强大的协议

时间:2016-10-24 19:55:56

标签: swift

我正在尝试转换以下Swift 2.3代码:

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

    /// Finds such index N that predicate is true for all elements up to
    /// but not including the index N, and is false for all elements
    /// starting with index N.
    /// Behavior is undefined if there is no such N.
    func binarySearch(predicate: Generator.Element -> Bool)
        -> Index {
        var low = startIndex
        var high = endIndex
        while low != high {
            let mid = low.advancedBy(low.distanceTo(high) / 2)
            if predicate(self[mid]) {
                low = mid.advancedBy(1)
            } else {
                high = mid
            }
        }
        return low
    }
}

进入Swift 3如下:

//Example usage:
//(0 ..< 778).binarySearch { $0 < 145 } // 145
extension Collection where Index: Strideable {

    /// Finds such index N that predicate is true for all elements up to
    /// but not including the index N, and is false for all elements
    /// starting with index N.
    /// Behavior is undefined if there is no such N.
    func binarySearch(predicate: (Generator.Element) -> Bool)
        -> Index {
        var low = startIndex
        var high = endIndex
        while low != high {
            let mid = low.advanced(by: low.distance(to: high) / 2)
            if predicate(self[mid]) {
                low = mid.advanced(to: 1)
            } else {
                high = mid
            }
        }
        return low
    }
}

错误

  

二元运算符&#39; /&#39;不能应用于自我类型的操作数.Index.Stride&#39;和&#39; Int&#39;

投放在let mid = low.advanced(by: low.distance(to: high) / 2)

有关如何修复它的任何帮助吗?

1 个答案:

答案 0 :(得分:5)

在Swift 3中,“集合移动他们的索引”,比较  关于斯威夫特进化的A New Model for Collections and Indices。特别是,您不要在索引上调用advancedBy(), 但是在集合上使用index()方法来推进索引。

所以你的方法将在Swift 3中实现

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
    }
}

同样的方法也可以编译(和工作)作为扩展 更一般的Collection类型,但是 - 正如Vadim Yelagin正确评论的那样, 如果无法进行索引/偏移计算,效率非常低 恒定的时间。