0

I've implemented the following to add functionality to [Float]

extension CollectionType where Generator.Element == Float, Index == Int, Index.Distance == Int {
    func sum() -> Float {
        return self.reduce(0,combine: +)
    }
    var addThem:Float {
        return self.reduce(0,combine: +)
    }
}

This seems to work, so I can now do this

let x:[Float] = [1, 2, 3]

x.sum()         // 6
x.addThem       // 6

All is good.

But when I added this to the extension

 func doesSomething() {
    var data = self
    let background = [Float](count: self.count, repeatedValue: 0)
    // Compiler does not like this statement
    data = background
}

Playground complains that "[Float] is not convertible to Self."

When I change the code to this

     let background = [Generator.Element](count: self.count, repeatedValue: 0)

Playground responds with "Cannot call value of non-function type [Float.Type]."

And then I tried this

     let background:[Generator.Element] = [Float](count: self.count, repeatedValue: 0)

which gives the same "[Float] is not convertible to Self" syntax error when I assign data = background.

What do I need to do to assign a [Float] or an equivalent to variable data and what is self in the above extension?

Epsilon
  • 1,016
  • 1
  • 6
  • 15

1 Answers1

0

As previously mentioned, you can do this to sort of get it to work:

func doesSomething() {
    var data = self
    let background = [Float](count: self.count, repeatedValue: 0)
    // Compiler does not like this statement
    data = background as! Self
}

Though this will only work if the Collection happens to be a Float array.

I don't believe you'll be able to initialized the specific type of the collection because (as far as I know) There are no "required" initializers in the collection protocol.

GetSwifty
  • 7,568
  • 1
  • 29
  • 46