Ada range sub typing in Swift

(Jonathan Prescott) #1

I'm looking for some advice on best to implement Ada subtype range constraints in Swift. In Ada, you can declare a subtype of a type that can optionally be constrained to a range of the super type's range, e.g.,

subtype BoundedInt is Integer range -10 .. 10
subtype ReallyBoundedInt is BoundedInt range -5 .. -5
subtype Probability is Real range 0.0 .. 1.0

with similar expressions to cases of enumerations, etc.. I can approximate subtypes like this for enumerable types like integers in C++ using templates and overloading the integer operators to ensure that bounds are maintained. The C++ floating point analogs are more clumsy to use since one cannot pass floating point constants as template parameters, but you can do it.

The beauty of this type of subtype is that instances of the subtype behave as the super-type: a BoundedInt can be added to another BoundedInt (or an Integer, if you want), for example.

I'm relatively new to Swift, so I'm looking for some guidance as to how one might implement such a concept.

As an aside, has there been any consideration of such a typing mechanism been considered as part of the language standard?

#2

What you are looking for are refinement types which is a subconcept of dependent types. This afaics not possible not possible in swift.

I'm relatively new to Swift, so I'm looking for some guidance as to how one might implement such a concept.

The best way to do it would be the use of enum types by filling it with all the needed elements of the refinement.:

e.g.:

 enum BoundedInt:Int
{
    case a=1
    case b=2
    case c=3
}
print("Hello, World!")
let bI:BoundedInt=BoundedInt.a
let i:Int=bI.rawValue
#3

Non type Generics might be able to simulate them to some extent.