简体   繁体   English

如何在Swift2中使用泛型类型

[英]How to use Generic type in Swift2

I'm not familiar with the generic type in swift and then I try to study and practice but I encountered an error in compiler. 我不熟悉Swift的通用类型,然后尝试学习和练习,但是在编译器中遇到错误。 take a look addNewType() method in ObjectA class. 看一下ObjectA类中的addNewType()方法。 Does anyone can help me? 有人可以帮助我吗? thanks! 谢谢!

class TypeA: NSObject {

    override init() {
        print("typeA")
    }
}

class ObjectA<T: TypeA>: NSObject {

    var type = [T]()

    init(type:T) {
        self.type.append(type)
    }

    func addNewType() {
        let newType = TypeA()
        self.type.append(newType) <-- Cannot invoke "append" with an argument list of type '(TypeA)'
    }
}

type is an array of type T . type是类型T的数组。 That means all elements must be of type T . 这意味着所有元素都必须是T类型。 In the addNewType() method, you try appending an element of type TypeA to the array of type T . addNewType()方法中,尝试将TypeA类型的元素追加到T类型的数组。 That is a type mismatch. 那是类型不匹配。 You can only put T s in the array, but you are trying to add a TypeA . 您只能将T放入数组中,但是您尝试添加TypeA This causes the error. 这会导致错误。

If you want to let TypeA s be put in the array as well then define it as var type = [TypeA]() . 如果还要将TypeA放入数组,则将其定义为var type = [TypeA]() Because T is defined to be a subclass of TypeA , you can then put instances of both T and TypeA in the array. 由于T被定义为TypeA的子类,因此您可以将TTypeA实例都放入数组中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM