[英]Storing Structs in a Generic Array
I'm trying to create a struct
which acts as a storage for the results being returned from a web API.我正在尝试创建一个struct
来存储从 Web API 返回的结果。 This API returns different JSON
results which are modeled as a set of struct
s.此 API 返回不同的JSON
结果,这些结果被建模为一组struct
。
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.这些结果需要存储在存储class
内部的数组中,该数组需要是通用的,因为它应该能够存储返回的任何类型的数组。 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
:
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:这些是两个示例structs
,对提到的 API 将返回的内容进行建模:
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:最后,这是我创建的协议,用于指定所有这些structs
都是同一个 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.它被抛出到FooStorage
类的storage.append(_:)
方法上。 Tried to add Equatable
and Hashable
conformance to the FooX
protocols but to no avail.尝试将Equatable
和Hashable
一致性添加到FooX
协议,但无济于事。 Seems I need some enlightenment here… thanks in advance!看来我需要一些启发......提前谢谢!
In your add function, remove the generic part & let it use the class
generic:在您的 add 函数中,删除泛型部分并让它使用泛型class
:
class FooStorage<F: Fooable> {
private var storage: [F] = []
func add(_ someFoo: F) {
storage.append(someFoo)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.