0

I have a method with signature:

func relatedObject<T: SomeType>(for type: T.Type) -> SomeRelatedObject

I have a SomeType.Type variable, and I want to call the method somehow, like:

let typeVariable: SomeType.Type = ...
let result = relatedObject(for: typeVariable)

but I get an error:

Cannot invoke 'relatedObject' with an argument list of type '(for: SomeType.Type)'

Is it possible to actually invoke the method somehow having a type variable?

Hamish
  • 78,605
  • 19
  • 187
  • 280
bartlomiej.n
  • 500
  • 6
  • 19
  • 1
    Is `SomeType` a protocol? (if it's a concrete type, your code should work). Compare [Why can't I pass a Protocol.Type to a generic T.Type parameter?](https://stackoverflow.com/q/45234233/2976878) – Hamish Aug 01 '17 at 12:37
  • That's true, it is a protocol. Thanks! Didn't know there is a difference. – bartlomiej.n Aug 01 '17 at 12:43

1 Answers1

0

You need to call it like this

relatedObject(for: SomeType.self) 

Here instead of SomeType you can pass any class/struct that conforms to SomeType. Lets say your CustomClass conforms to SomeType then you can pass it like

relatedObject(for: CustomClass.self)
Mohammad Sadiq
  • 5,070
  • 28
  • 29
  • But OP wants to pass a `SomeType.Type` to the function, not a `SomeType.Protocol` (which is what `SomeType.self` is in this case). – Hamish Aug 01 '17 at 15:52