你需要做至少2个功能:一是为SignedIntegerType
,一个用于UnsignedIntegerType
。
SignedIntegerType
有类型强制转换功能:toIntMax()
和init(_: IntMax)
protocol _SignedIntegerType : _IntegerType, SignedNumberType {
/// Represent this number using Swift's widest native signed integer
/// type.
func toIntMax() -> IntMax
/// Convert from Swift's widest signed integer type, trapping on
/// overflow.
init(_: IntMax)
}
UnsignedIntegerType
还键入胁迫功能:toUIntMax()
和init(_: UIntMax)
protocol _UnsignedIntegerType : _IntegerType {
/// Represent this number using Swift's widest native unsigned
/// integer type.
func toUIntMax() -> UIntMax
/// Convert from Swift's widest unsigned integer type, trapping on
/// overflow.
init(_: UIntMax)
}
使用这些功能,您可以:
func randomNumber<T: UnsignedIntegerType>(min: T, max: T) -> T {
let n = max - min + 1
let u = UInt32(n.toUIntMax())
let r = arc4random_uniform(u)
return T(r.toUIntMax()) + min
}
func randomNumber<T: SignedIntegerType>(min: T, max: T) -> T {
let n = max - min + 1
let u = UInt32(n.toIntMax())
let r = arc4random_uniform(u)
return T(r.toIntMax()) + min
}
但是,我们已经有了得心应手numericCast
内建函数:
func numericCast<T : _UnsignedIntegerType, U : _SignedIntegerType>(x: T) -> U
func numericCast<T : _SignedIntegerType, U : _UnsignedIntegerType>(x: T) -> U
func numericCast<T : _UnsignedIntegerType, U : _UnsignedIntegerType>(x: T) -> U
func numericCast<T : _SignedIntegerType, U : _SignedIntegerType>(x: T) -> U
numericCast
可以简化您的实现:
func randomNumber<T: UnsignedIntegerType>(min: T, max: T) -> T {
return min + numericCast(arc4random_uniform(numericCast(max - min + 1)))
}
func randomNumber<T: SignedIntegerType>(min: T, max: T) -> T {
return min + numericCast(arc4random_uniform(numericCast(max - min + 1)))
}
内numericCast
转换T
到UInt32
,外一个转换UInt32
到T
。
现在,这些函数具有完全相同的实现代码:)但我认为你不能将它们统一成一个函数。