I am trying to call a function for each element of an array of mixed elements conforming to a same protocol.
Please consider the following code, the export
and exportA
compile fine but as soon as I add a requirement that Database
inherits from a class then exportB
won't compile.
My first assumption is that everything below should compile but maybe there's something more than I don't get.
So, what am I doing wrong and is there any way to make it work with a class inheritance constraint ?
Thanks
protocol DatabaseExporter<Database> {
associatedtype Database
func export(database: Database)
}
func export<Database>(database: Database, usingExporters exporters: [any DatabaseExporter<Database>]) {
for exporter in exporters {
exporter.export(database: database)
}
}
protocol A {}
func exportA<Database: A>(database: Database, usingExporters exporters: [any DatabaseExporter<Database>]) {
for exporter in exporters {
exporter.export(database: database)
}
}
class B {}
func exportB<Database: B>(database: Database, usingExporters exporters: [any DatabaseExporter<Database>]) {
for exporter in exporters {
exporter.export(database: database) /// Error : Member 'export' cannot be used on value of type 'any DatabaseExporter<Database>'; consider using a generic constraint instead
exportB(database: database, usingExporter: exporter) /// Error : Global function 'exportB(database:usingExporter:)' requires that 'Database' inherit from 'B'
}
}
func exportB<Database: B>(database: Database, usingExporter exporter: some DatabaseExporter<Database>) {
exporter.export(database: database)
}