1

In my init function, I have:

 self.x = [T](count: dimensions, repeatedValue: 0)

This does not work. How do I get this to work.

I want x to be an array with type T that is initialized to 0. (T is intuitively like Int but could be some other number representation.)

user678392
  • 1,981
  • 3
  • 28
  • 50

1 Answers1

6

your code works, you just have to make sure T can be converted from 0 (IntegerLiteralConvertible)

func test<T: IntegerLiteralConvertible>(dimensions: Int) -> [T] {
    return [T](count: dimensions, repeatedValue: 0)
}

println(test(3) as [Int]) //[0, 0, 0]
println(test(3) as [Double]) //[0.0, 0.0, 0.0]

or somehow make sure val have type of T

func test<T>(dimensions: Int, val: T) -> [T] {
    return [T](count: dimensions, repeatedValue: val)
}

println(test(3, 1)) //[1, 1, 1]
println(test(3, "a")) //[a, a, a]
Bryan Chen
  • 45,816
  • 18
  • 112
  • 143