0

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?

1

1 Answer 1

2

Inspired by the answer provided by @MartinR I came up with the following solution

extension Array {
    init<T>(_ array: [T]) where Element == MyGeneric<T> {
        self.init(array.map(MyGeneric.init))
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

The constraint on T is not needed, apparently the compiler infers it from the definition of MyGeneric. So init<T>(_ array: [T]) where Element == MyGeneric<T> is sufficient.
@MartinR Thanks, I didn't even consider 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.