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

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.