如何扩展数组<Double>?

How to extend an Array<Double>?

Element 类型 Double 扩展 Array 的语法是什么?

我见过这样的回答:

extension Sequence where Iterator.Element == Double {
    public func multiply(by factor: Double) -> [Double] {
        return self.map { [=11=] * 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[[=12=]] * windowingFunc(index: [=12=], N: self.count)}
    }
}

我通过添加很多约束来让它工作:

extension RandomAccessCollection where Iterator.Element == Double, IndexDistance == Int, Index == Int {
    public func applyWindowing() -> [Double] {
        return (0..<self.count).map{self[[=10=]] * windowingFunc(index: [=10=], N: self.count)}
    }
}

IndexDistance == Int 生成 count Int 的类型。 Index == Int 使您可以使用 Int.

访问数组

如果你想映射你的数组元素并且还需要它的索引位置,你应该使用方法enumerated()。我还会扩展 BidirectionalCollection 而不是 RandomAccessCollection 并且正如@Hamish 在评论中已经提到的那样,您可以省略 Index == Int 约束。

protocol BidirectionalCollection : BidirectionalIndexable, Collection

Description: A collection that supports backward as well as forward traversal. Bidirectional collections offer traversal backward from any valid index, not including a collection’s startIndex. Bidirectional collections can therefore offer additional operations, such as a last property that provides efficient access to the last element and a reversed() method that presents the elements in reverse order. In addition, bidirectional collections have more efficient implementations of some sequence and collection methods, such as suffix(_:).

extension BidirectionalCollection where Iterator.Element == Double, IndexDistance == Int {
    public func applyWindowing() -> [Iterator.Element] {
        return enumerated().map{ [=11=].element * windowingFunc(index: [=11=].offset, N: count)}
    }
}