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]();
}
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
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