[英]How to save generic object to an array in swift
I have on class 我上课
class SomeClass<T>: AsyncOperation, NetworkOperationProtocol {
/// The resource model object that conforms to Parsable Response
public typealias Resource = T
}
I want to save instance of this class to an array, and want retrieve it later. 我想将此类的实例保存到数组中,并希望以后再检索它。 How can I achieve this?
我该如何实现?
If your generic type would be: 如果您的通用类型为:
struct GenericType {}
You would specify the generic class using: 您可以使用以下方式指定通用类:
let array = [SomeClass<GenericType>]()
Or you can let it infer the type on its own with something like: 或者,您可以让它自己通过以下方式推断类型:
class SomeClass<T>: AsyncOperation, NetworkOperationProtocol {
/// The resource model object that conforms to Parsable Response
public typealias Resource = T
let resource: Resource
init(with resource: Resource) {
self.resource = resource
}
}
let item = SomeClass(with: GenericType())
let array = [item]
It should be simple You can declare an array like this 应该很简单您可以这样声明一个数组
var anArray = [SomeClass<Parsable>]()
Please note that while declaring the array I have defined the Parsable
instead of T. 请注意,在声明数组时,我定义了
Parsable
而不是T。
If you don't know the type of T while creating array. 如果在创建数组时不知道T的类型。 You can go following way
你可以走下面的路
var anArray = [AnyObject]()
let anObject = SomeClass<Parsable>()
anArray.append(anObject)
if anArray[0] is SomeClass<Parsable> {
print(true)
}
If your class implements protocol with associatedtype, it's impossible to put it into array because such protocols have Self-requirement - they need to know concrete type for associatedtype. 如果您的类使用associatedtype实现协议,则无法将其放入数组中,因为此类协议具有自我要求-他们需要知道associatedtype的具体类型。
However, you can use technique called type-erasure to store type without associated type information. 但是,您可以使用称为类型擦除的技术来存储没有关联类型信息的类型。 So, for example, you can create a protocol without associatedtype, like so
因此,例如,您可以创建一个没有关联类型的协议,像这样
protocol Operation {
func perform()
}
class SomeClass<T> : AsyncOperation, NetworkOperationProtocol, Operation
And then define an array of such operations: 然后定义一个这样的操作数组:
let operations : [Operation] = []
operations.append(SomeClass.init())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.