Is there a "cardinal number" type that I can use for Generics?

Hi!

Is there a way to use generics to force an integer constraint on class instances for type checking?

For example, I am currently writing the following for n-ary objects (n-ary objects can only interact with each other if their arity matches):

class NAryThing {
    let arity: Int
    init(arity: Int) {
        self.arity = arity
    }
}

The problem: I can only detect an error at run-time. Let's say, when a 2-ary object interacts with a 3-ary object.

What I would like to write is:

class NAryThing<ArityType> {
    ...
}

So, now I could create instances with NAryThing<Arity2> and NAryThing<Arity3>, which would tell me about arity mix-ups at compile time.

I could create classes for some ArityType just like given above, but I think that is a bit clunky. It also means that there is an upper bound to the arity -- since I can only define a finite number of arity classes (Arity1, Arity2, ..., ArityM).

Is there a way to implement this, but have access to the whole Int range with out typing out 2^64 class definitions?

Thanks,

Kim

Search the forums for variadic generics, and you'll find lots of discussions on the topic.
The short answer is: Swift cannot currently do what you ask, without some form of meta programming.

1 Like

Awesome! Thank you for the quick reply and for giving a name to the problem that I'm trying to solve!

What you’re actually looking for are generic value parameters (i.e. the ability to use an Int value as part of a type), rather than variadics. Unfortunately the answer is the same - they are not yet supported by Swift, but hopefully will be, one day!

6 Likes

I read through variadic generics now and you are spot on! I would need generic value parameters to solve my problem at compile time.

Another way to solve this without implementing generic value parameters would be compile-time evaluation, where your run-time errors that dynamically enforce matching arities could be turned into compile-time errors. There have been discussions and steps towards this in the past, but I think they were being driven by the Swift for Tensorflow team which has since been disbanded.

1 Like
Terms of Service

Privacy Policy

Cookie Policy