我正在尝试转换以下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
}
}误差
二进制运算符'/‘不能应用于'self.Index.Stride’和'Int‘类型的操作数
向let mid = low.advanced(by: low.distance(to: high) / 2)抛出
有什么能帮上忙的吗?
发布于 2016-10-24 20:28:04
在Swift 3中,“集合移动他们的索引”,比较一种新的馆藏与指数模型关于Swift的演变。特别是,您不对索引调用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类型的扩展,但是- as Vadim Yelagin正确地指出,如果索引/偏移量计算不能在固定时间内完成,则效率很低。
https://stackoverflow.com/questions/40226479
复制相似问题