4

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.

cfischer
  • 24,452
  • 37
  • 131
  • 214

2 Answers2

3

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.

Alexander
  • 59,041
  • 12
  • 98
  • 151
0

you can use stored property to store actual value and use Computed Property to get and set value to stored property . So do some validation in set in Computed Property . that way u can restrict the value

Keaz
  • 955
  • 1
  • 11
  • 21