Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of undeclared type 'T' when declared array of any type in Swift

I'm trying to declare a property with an array of any type T. But I'm getting compiler error - Use of undeclared type 'T'. Below is the class that I created with 2 properties.

class Product {
 var productName: String;
 var items: Array<T>
}

Please let me know how to declare an array of any type using Generics in Swift. I've tried the below options:

{
var items: Array<T>;
var items = Array<T>();
var items = [T]();
}
like image 772
user3187840 Avatar asked Dec 11 '25 01:12

user3187840


1 Answers

You have to define the generic type in the class declaration:

class Product<T> {
    var productName: String;
    var items: Array<T>
}

Of course, since the class has uninitialized non optional variables, you have to either initialize them inline:

class Product<T> {
    var productName: String = ""
    var items: Array<T> = Array<T>()
}

make them optionals:

class Product<T> {
    var productName: String?
    var items: Array<T>?
}

define an initializer:

class Product<T> {
    var productName: String
    var items: Array<T>

    init(productName: String, items: Array<T>) {
        self.productName = productName
        self.items = items
    }
}

or any combination of them.

Note that the trailing semicolon is not required in swift, unless you put more than one statement in the same line

like image 107
Antonio Avatar answered Dec 13 '25 15:12

Antonio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!