user3894009 user3894009 - 2 months ago 29
Swift Question

Swift 3 extension with a floating point array

I'm trying to extend an

Array<Float>
in Swift 3. The goal is to add a function and call a few
self.append()
statements in the body. Here's what I have so far:

extension Array where Element: FloatingPoint {

mutating func test(a: Float) {
self.append(a)
}

}


I'm getting an error that
append()
needs a
FloatingPoint
, and that it cannot use
Float
. But doesn't the
Float
type conform to
FloatingPoint
? Btw in Swift 2.X, I extended
_ArrayType
which worked well. It seems to have disappeared in Swift 3, and the
append()
function is now in
Array
.

Answer

You can only append elements to the array of type Element:

extension Array where Element: FloatingPoint {

    mutating func test(a: Element) {
        self.append(a)
    }

}

Note: This extension extends all floating point arrays: [Double], [CGFloat], ...