加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – Stridable Protocol

发布时间:2020-12-14 05:33:12 所属栏目:百科 来源:网络整理
导读:我试图转换以下 Swift 2.3代码: //Example usage://(0 .. 778).binarySearch { $0 145 } // 145extension CollectionType where Index: RandomAccessIndexType { /// Finds such index N that predicate is true for all elements up to /// but not includ
我试图转换以下 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
    }
}

错误

Binary operator ‘/’ cannot be applied to operands of type ‘self.Index.Stride’ and ‘Int’

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

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

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

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

extension Collection {

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

不需要对索引类型进行任何限制.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读