Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a type bound to a certain range in Swift

Say I have a function that takes an Int, but not just any Int. It could be:

  • Only natural numbers
  • Ints from 2 to 200
  • etc

Assume that the number of valid values is too big to make the use of an Enum that explicitly declares all of them a feasible approach.

Is there a way to declare a type that specifies a closed range in Swift?

I tried playing around with Range, but it doesn't work as expected.

like image 360
cfischer Avatar asked Oct 24 '25 12:10

cfischer


1 Answers

The best I can think of is to wrap an Int in a struct with an initializer that enforces your condition:

struct NameMe {
    let value: Int

    init?(_ value: Int) {
        guard 2...200 ~= value else { return nil }
        self.value = value
    }
}

Whereas using Int alone would require a run-time condition check at every place a value of such a kind was needed, this technique limits this to only the places where such values are created in the first place. Once created, you can pass around NameMe instances around, knowing that their value meets the preconditions.

like image 75
Alexander Avatar answered Oct 26 '25 04:10

Alexander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!