[英]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.