Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apple Swift: Initialize Array of Generic Type

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.

like image 640
nalyd88 Avatar asked Feb 13 '23 18:02

nalyd88


1 Answers

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)
like image 173
John Bates Avatar answered Feb 15 '23 11:02

John Bates