简体   繁体   中英

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.

If you don't know the type of T while creating array. 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.

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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