Disclaimer
Please note this is only a simplified example. Actual problem is a bit more complex so I need actual Array extension rather than other solution. I know that
let mapped: [MyGeneric<Int>] = items.map { .init(someVariable: $0) }
will work, but I'm looking for a way to write generic array extension not fix this simplified code
Problem
I'm trying to write a generic extension to an array/collection as below:
struct MyGeneric<T: Hashable> {
let someVariable: T
}
Expected output
Code below is not working because I'm missing Array extension, but ideally my output would be something like this:
let items: [Int] = [1, 2, 3, 4, 5]
let mapped: [MyGeneric<Int>] = .init(items)
So what I need is:
extension [MyGeneric<Hashable>] {
init(someArray: [some Hashable]) {
self = someArray.map { MyGeneric(someVariable: $0)}
}
}
but of course this is not compiling because generic parameter from extension is not passed to init generic parameter. How can I pass the type from extension to functions in that. Can I use somehow Element.Type in this one and extract Generic type from there? Or maybe there is an extension Array where ... syntax that I'm not familiar with?