I have an array (member of a class) of generic type T. The generic type will only be numeric types (double, int, etc). My question is how to initialize this array to all the same number in the initializer?
I've seen this:
self.data = Double[](count: 3, repeatedValue: 1.0)
So I tried this but it doesn't work...
self.data = T[](count: 3, repeatedValue: 1.0)
Anybody know how to do this? Thanks.
So, here's what I just did:
protocol Initable {
init()
}
class Bar:<T: Initable> {
var ar: T[]
init(length: Int) {
self.ar = T[](count:length, repeatedValue: T())
}
}
Then you just have to make sure that any T
that you use implements the Initable
protocol, e.g.:
extension Int:Initable {}
which lets me do this:
var foo = Bar<Int>(3)
I also used a prototyping alternative:
class Bar:<T> {
var ar: T[]
init(length: Int, proto:T) {
self.ar = T[](count:length, repeatedValue:proto)
}
}
which doesn't require the protocol, but does need a supplied initial value:
var foo = Bar<Int>(length: 3, proto: 34)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With