在 Swift 或任何其他自定义整数或浮点自定义类型中实现 UInt15

问题描述

是否有一种简单的方法来实现一个数值类型(整数或浮点数),该类型限制了您可以分配给它的值。我的最终目标是拥有一个 UInt15 类型,它是 032767 之间的整数以及其他类似类型。

例如我可以执行以下操作:

    typealias HumanAge = Int

通过这种方式,我确保年龄始终是一个整数。

如果我这样做:

    typealias HumanAge = UInt8

不错,现在它被限制为 0255 之间的一个无符号整数。

但是人类活不了那么久,所以我如何实现一个 HumanAge 类型,它是一个无符号的 Int 并且被限制在 0100 之间,或者例如一个 TeenAge 类型,它是一个在 Int13 之间约束的无符号 19

解决方法

这对您的问题来说可能有点矫枉过正,但我​​想属性包装器应该能够在这里为您提供帮助


@propertyWrapper struct AgeRestrictedInt {
    var range = 0 ... 100
    var wrappedValue: Int? = nil {
        didSet { if let unwrappedValue = wrappedValue {
            if range ~= unwrappedValue {
                return
            }
            else {
                wrappedValue = nil
            }
        }
        }
    }
}

您现在可以声明您的年龄为

@AgeRestrictedInt var normalHumanAge: Int?
@AgeRestrictedInt(range: 13 ... 19) var teenAge: Int?

现在如果你给这些变量赋值

        self.normalHumanAge = 1
        debugPrint(self.normalHumanAge) // optional (1)
        self.normalHumanAge = 500
        debugPrint(self.normalHumanAge) // nil

同样

        self.teenAge = 14
        debugPrint(self.teenAge) //optional (14)
        self.teenAge = 30
        debugPrint(self.teenAge) // nil

您可以为每个变量指定自定义范围值,并且您可以决定如果分配的值超出指定的范围(例如这里将其设置为 nil

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...