I’m trying to create a struct
which acts as a storage for the results being returned from a web API. This API returns different JSON
results which are modeled as a set of struct
s.
These results need to be stored in an array inside of a storage class
which will need to be generic as it should be able to store arrays of any of the types returned. I’m struggling, however, with adding generic data to an array… and this is where you guys might come in.
This is the storage class
:
class FooStorage<F: Fooable> {
private var storage: [F] = []
func add<F: Fooable>(_ someFoo: F) {
storage.append(someFoo)
}
}
These are two sample structs
modeling what the API mentioned will return:
struct FooA: Fooable, Decodable {
var foo: String
}
struct FooB: Fooable, Decodable {
var foo: String
var bar: String
}
And finally, this is the protocol I created in order to specify that all of these structs
are results of the same API:
protocol Fooable {}
The compiler error I get is this:
No exact matches in call to instance method append
And it is thrown on the storage.append(_:)
method of the FooStorage
class. Tried to add Equatable
and Hashable
conformance to the FooX
protocols but to no avail. Seems I need some enlightenment here… thanks in advance!
CodePudding user response:
In your add function, remove the generic part & let it use the class
generic:
class FooStorage<F: Fooable> {
private var storage: [F] = []
func add(_ someFoo: F) {
storage.append(someFoo)
}
}