3

How would one extend an array of structs that have a generic type? Please see the below code for what I am trying to do.

struct MyStruct<T: MyProtocol> {
   ...
}

extension Array where Element: MyStruct<T> { // Not sure if T is supposed to be on this line.

    func doWork() -> [T] {
        ...
    }
}

Basically, how would I write the extension to have a method return an array of the generic type passed into the struct.

1 Answer 1

9

You will need to create a protocol with an associated type:

protocol MyGenericStructProtocol {
    associatedtype GenericParameter
}

Let your struct adopt the protocol, either directly, or using an extension:

extension MyStruct: MyGenericStructProtocol {
    typealias GenericParameter = T
}

Now you can reference the generic type inside your extension of Array:

extension Array where Element: MyGenericStructProtocol {
    func doWork() -> [Element.GenericParameter] {
        return []
    }
}

Check out a fully working example on this GitHub gist

Sign up to request clarification or add additional context in comments.

Comments

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.