2016-10-24 129 views
2

我想下面的雨燕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)

有關如何解決它的任何幫助?

+0

您的Swift 2代碼來自http://stackoverflow.com/a/33674192/1187415?如果從其他來源引用代碼,則應該添加一個鏈接到原件。 –

+0

是的,感謝您找到鏈接。我無法追查。 – Navi

回答

4

在Swift 3中,「Collections移動它們的索引」,比較 A New Model for Collections and Indices對Swift進化的影響。尤其是,您不要在索引 上調用advancedBy(),而是在集合上使用index()方法來推進索引。

所以你的方法將在斯威夫特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 
    } 
} 

,而無需在索引類型的任何限制。

+0

謝謝。這很奇妙。 – Navi