[英]How to extend an Array<Double>?
擴展具有Double
類型的Element
的Array
的語法是什么?
我已經看到了這樣的答案:
extension Sequence where Iterator.Element == Double {
public func multiply(by factor: Double) -> [Double] {
return self.map { $0 * factor }
}
}
但是,它擴展了通用Sequence
,因此它既不允許按索引隨機訪問,也不允許count
屬性。 因此,例如,我無法實現以下內容:
public func windowingFunc(index: Int, N: Int) -> Double {
// ...
}
extension Sequence where Iterator.Element == Double {
public func applyWindowing() -> [Double] {
return (0..<self.count).map{self[$0] * windowingFunc(index: $0, N: self.count)}
}
}
如果要映射數組元素並且還需要其索引位置,則應使用enumerated()
方法。 我還將擴展BidirectionalCollection
而不是RandomAccessCollection
,正如@Hamish在注釋中使用枚舉已提到的那樣,您可以省略Index == Int
約束。
protocol BidirectionalCollection : BidirectionalIndexable, Collection
說明:一個集合,它支持向后和向前遍歷。 雙向集合提供從任何有效索引向后遍歷的功能,但不包括集合的startIndex。 因此,雙向集合可以提供其他操作,例如提供有效訪問最后一個元素的last屬性和以相反順序顯示元素的reversed()方法。 此外,雙向集合對某些序列和集合方法(例如后綴(_ :))具有更有效的實現。
extension BidirectionalCollection where Iterator.Element == Double, IndexDistance == Int {
public func applyWindowing() -> [Iterator.Element] {
return enumerated().map{ $0.element * windowingFunc(index: $0.offset, N: count)}
}
}
我通過添加很多約束來使其工作:
extension RandomAccessCollection where Iterator.Element == Double, IndexDistance == Int, Index == Int {
public func applyWindowing() -> [Double] {
return (0..<self.count).map{self[$0] * windowingFunc(index: $0, N: self.count)}
}
}
IndexDistance == Int
使count
類型為Int
。 Index == Int
使您可以使用Int
訪問數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.