首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >可扩展协议

可扩展协议
EN

Stack Overflow用户
提问于 2016-10-24 19:55:55
回答 1查看 1.5K关注 0票数 3

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

代码语言:javascript
复制
//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的步骤如下:

代码语言:javascript
复制
//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
    }
}

误差

二进制运算符'/‘不能应用于'self.Index.Stride’和'Int‘类型的操作数

let mid = low.advanced(by: low.distance(to: high) / 2)抛出

有什么能帮上忙的吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-10-24 20:28:04

在Swift 3中,“集合移动他们的索引”,比较一种新的馆藏与指数模型关于Swift的演变。特别是,您不对索引调用advancedBy(),而是调用集合上的index()方法来提前索引。

因此,您的方法将在Swift 3中实现为

代码语言:javascript
复制
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类型的扩展,但是- as Vadim Yelagin正确地指出,如果索引/偏移量计算不能在固定时间内完成,则效率很低。

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40226479

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档