1

I need to get the generic type of an array.

I have an object that is an Array<Decodable>, but I am not guaranteed that the generic type is always Decodable. I know I can get the type of the thing by saying array.self.dynamicType to get the Array.Type, but I need something like array.generic.self.dynamicType to get Decodable.Type. How would I do this?

2
  • 1
    How did you get only Array.Type to print? print([1, 2, 3].dynamicType) yields Array<Int>, not just Array. If you expect quality answers, you'll have to give use a more concrete, minimal, complete, and verifiable example. Commented Sep 28, 2016 at 16:32
  • @AlexanderMomchliov Yeah it does give Array<Int>, but that is of Array.Type. Should have clarified better. That seems irrelevant though, given that I don't care about that piece. I just want the generic type. Commented Sep 28, 2016 at 16:35

1 Answer 1

1

You can extend Array with a computed property that exposes its generic type parameter Element:

extension Array {
    var ElementType: Element.Type {
        return Element.self
    }
}

print([1, 2, 3].dynamicType) //Array<Int>
print([1, 2, 3].ElementType) //Int
Sign up to request clarification or add additional context in comments.

3 Comments

I'll give this a shot. Looks like it could do what I need.
It certainly works, but I'm still searching for a better way
Ran into a issue with casting too, which I kind of have to do. If you've got thoughts I'd appreciate them. Posted a new questions, since technically this answer this questions just fine. stackoverflow.com/questions/39753881/…

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.