Creating a type bound to a certain range in Swift

。_饼干妹妹 提交于 2019-12-22 12:15:18

问题


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.


回答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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!