我想下面的雨燕2.3的代碼轉換:Stridable協議
//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
}
}
到斯威夫特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)
有關如何解決它的任何幫助?
您的Swift 2代碼來自http://stackoverflow.com/a/33674192/1187415?如果從其他來源引用代碼,則應該添加一個鏈接到原件。 –
是的,感謝您找到鏈接。我無法追查。 – Navi