在Swift中声明任何类型的数组时使用未声明类型'T'

时间:2023-01-23 17:48:05

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.

我试图声明一个具有任意类型T的数组的属性,但是我得到了编译错误——使用未声明的类型'T'。下面是我用两个属性创建的类。

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:

请告诉我如何在Swift中使用泛型声明任何类型的数组。我试过下面的选项:

{
var items: Array<T>;
var items = Array<T>();
var items = [T]();
}

1 个解决方案

#1


5  

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

注意,swift中不需要后面的分号,除非在同一行中放置多个语句

#1


5  

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

注意,swift中不需要后面的分号,除非在同一行中放置多个语句