简体   繁体   中英

How to extend an Array<Double>?

What's the syntax for extending an Array with an Element type of Double ?

I've seen this sort of answer around:

extension Sequence where Iterator.Element == Double {
    public func multiply(by factor: Double) -> [Double] {
        return self.map { $0 * factor }
    }
}

But it's extending a generic Sequence , so it allows neither random access by index, nor to a count property. So eg, I can't implement the following:

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)}
    }
}

If you want to map your array elements and need also its index position you should use the method enumerated() . I would also extend BidirectionalCollection instead of RandomAccessCollection and as already mentioned in comments by @Hamish using enumerated you can omit the Index == Int constraint.

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{ $0.element * windowingFunc(index: $0.offset, N: count)}
    }
}

I got this to work by adding lots and lots of constraints:

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 makes the type of count Int . Index == Int makes you access the array with Int .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM