Subtype of a generic type can't be used on its own?


I recently stumbled upon this issue, that you can't instantiate an "inner" type (not sure what the correct term here would be), which was declared as part of a generic type. Here is a small code sample to illustrate what I mean:

struct A<T> {
  var x: T
  struct Configuration {
    var c: Int
let cfg = A<Int>.Configuration(c: 1) // <- ERROR: Generic parameter T could not be inferred

Now I am wondering why that is and what the reasoning behind that is?
Thanks for any hints!

Cheers, Michael

That looks like a bug to me. Your example should be valid, because you explicitly provided the T = Int argument in the type reference.


Sorry my bad :-(. It is indeed valid. I accidentally pasted the working example from the Playground where I was playing with that code. The correct wrong coding is (as you probably expected):
let cfg = A.Configuration(c: 1) // <- Generic parameter T could not be inferred
Without the explicitly provided T = Int argument. That got me wondering why the "inner" type depends also on T without making use of it?

The type of A<Int>.Configuration is clear (that). What type would you expect a thing created with A.Configuration(c: 1) to be? It has to be something concrete and you’re not giving it a clue here to use to make a guess.

I think there are a few reasons compounding together.

It's true that A.Configuration doesn't use T, but you don't know that. It may be using private T under the hood which won't be visible from outside of the module. It'd be pretty hard to reason when you start relying on potentially invisible declarations.

Also, we probably want X<Int> to be different from X<String> even if there's no generic being used in the storage at all. Thing like unique identifier or snowflake would very much benefit from this. You don't want to mix ID<Person> and ID<Department> together even if they're just UInt64 under the hood.

Thanks for the replies! I guess I learned something :grinning:
I think where I got it wrong was, that in my mental model I treated the struct A<T> more like a namespace and not as a type - and that then led to all the wrong conclusions and assumptions.

Terms of Service

Privacy Policy

Cookie Policy