问题
Say I have a function that takes an Int, but not just any Int. It could be:
- Only natural numbers
Intsfrom 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.
回答1:
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.
回答2:
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
来源:https://stackoverflow.com/questions/42569279/creating-a-type-bound-to-a-certain-range-in-swift