在 Swift 或任何其他自定义整数或浮点自定义类型中实现 UInt15
Implementing UInt15 in Swift or any other custom integer or float custom type
是否有一种简单的方法来实现一个数字类型(整数或浮点数),它受限于您可以分配给它的值。我的最终目标是拥有一个 UInt15
类型,它是 0
和 32767
之间的整数以及其他类似类型。
例如我可以执行以下操作:
typealias HumanAge = Int
通过这种方式,我确保年龄始终是一个整数。
如果我这样做:
typealias HumanAge = UInt8
不错,现在它被限制为 0
和 255
之间的无符号整数。
但是人类不会活那么久,所以我将如何实现一个 HumanAge
类型,它是一个无符号的 Int
并且被限制在 0
和 100
之间或者例如TeenAge
类型,它是一个无符号 Int
,限制在 13
和 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
)
是否有一种简单的方法来实现一个数字类型(整数或浮点数),它受限于您可以分配给它的值。我的最终目标是拥有一个 UInt15
类型,它是 0
和 32767
之间的整数以及其他类似类型。
例如我可以执行以下操作:
typealias HumanAge = Int
通过这种方式,我确保年龄始终是一个整数。
如果我这样做:
typealias HumanAge = UInt8
不错,现在它被限制为 0
和 255
之间的无符号整数。
但是人类不会活那么久,所以我将如何实现一个 HumanAge
类型,它是一个无符号的 Int
并且被限制在 0
和 100
之间或者例如TeenAge
类型,它是一个无符号 Int
,限制在 13
和 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
)