[swift-evolution] [pitch] Add a NativeType type alias to Int/UInt
Martin R
martinr448 at gmail.com
Fri Apr 21 09:08:51 CDT 2017
Some algorithms depend on the size of the `(U)Int` type. A typical example are hashing
functions, as in Hashing.swift (https://github.com/apple/swift/blob/master/stdlib/public/core/Hashing.swift#L142)
func _mixInt(_ value: Int) -> Int {
#if arch(i386) || arch(arm)
return Int(_mixInt32(Int32(value)))
#elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x)
return Int(_mixInt64(Int64(value)))
#endif
}
I suggest to add a "NativeType" type alias to both Int and UInt. On a 64-bit platform this
would be
extension Int {
public typealias NativeType = Int64
}
extension UInt {
public typealias NativeType = UInt64
}
In the above example, the code would then simplify to
func _mixInt(_ value: Int32) -> Int32 { return value }
func _mixInt(_ value: Int64) -> Int64 { return value }
func _mixInt(_ value: Int) -> Int {
return Int(_mixInt(Int.NativeType(value)))
}
i.e. one can write size-dependent code without using platform conditions (which have to be
maintained for new platforms).
Note that a similar property already exists for CGFloat:
public struct CGFloat {
/// The native type used to store the CGFloat, which is Float on
/// 32-bit architectures and Double on 64-bit architectures.
public typealias NativeType = Double
}
Martin
More information about the swift-evolution
mailing list