Apple Swift: initialize a generic array

I have an array (class member) of general type T. The general type will be only numeric types (double, int, etc.). My question is how to initialize this array to the same number in the initializer?

I have seen that:

self.data = Double[](count: 3, repeatedValue: 1.0)

So, I tried this, but it does not work ...

self.data = T[](count: 3, repeatedValue: 1.0)

Does anyone know how to do this? Thank.

+4
source share
2 answers

So here is 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 need to make sure that anyone Tyou use implements the protocol Initable, for example:

extension Int:Initable {}

which allows me to do this:

var foo = Bar<Int>(3)

I also used an alternative to prototyping:

class Bar:<T> {
    var     ar: T[]

    init(length: Int, proto:T) {
        self.ar = T[](count:length, repeatedValue:proto)
    }
}

which does not require a protocol, but needs an initial value:

var foo = Bar<Int>(length: 3, proto: 34)
+8

, :

self.data = AnyObject[](count: 3, repeatedValue: 1.0)
0

Source: https://habr.com/ru/post/1543939/


All Articles