0

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?

1
  • You want an array of generic types? Something like [SomeClass<A>(), SomeClass<B>()]? If so, then it's impossible. Commented Dec 8, 2017 at 15:57

3 Answers 3

1

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())
Sign up to request clarification or add additional context in comments.

Comments

0

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]

Comments

0

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

2 Comments

What is Parsable here? I don't know type of T while retrieving.
In your question I saw in comment Parsable. Its just an example. You need to know the type of T while retrieving.use if..is for that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.