Say I have a function that takes an Int, but not just any Int. It could be:
Ints from 2 to 200Assume 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With