Search code examples
swiftgenericsswift-array

Is there a way to initialize an array in Swift to have a repeated value of some Type T


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


Solution

  • 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]