There are two properties called bitWidth
for FixedWidthInteger
s, one is a type property:
/// The number of bits used for the underlying binary representation of
/// values of this type.
///
/// The bit width of a `Int` instance is 32 on 32-bit
/// platforms and 64 on 64-bit platforms.
public static var bitWidth: Int { get }
The other one is an instance property:
/// The number of bits in the binary representation of this value.
public var bitWidth: Int { get }
This instance property is listed here as a default implementation of the above type property.
[1] Can a type property have a default implementation that is an instance property?
Also, it seems to me that the fact that it is not a type property together with its current documentation makes it easy to (mis)interpret as “The minimum number of bits required to represent this value in binary form” which would mean:
a.bitWidth == type(of: a).bitWidth - a.leadingZeroBitCount
// Or perhaps more intuitively:
a.bitWidth == String(a, radix: 2).count
But as it turns out the instance property is always the same as the type property, ie
a.bitWidth == type(of: a).bitWidth
So, given that the type property is (for some reason) duplicated as an instance property, [2] why hasn’t the formulation in the documentation for the type property simply been reused for the instance property? It would be much clearer:
/// The number of bits used for the underlying binary representation of
/// values of this type.
public var bitWidth: Int { get }
And, finally, [3] what motivates the instance property when it’s already available (more logically) as a type property?
I mean, there is for example a similar type property .significandBitCount
(in BinaryFloatingPoint
). Not only hasn’t it been duplicated as an instance property, but there is even an instance property called .significandWidth
which is very similar to my misinterpretation of .bitWidth
above:
/// The number of bits required to represent the value's significand.
/// ...
public var significandWidth: Int { get }
That is, the result of this instance property changes depending on the particular value / instance, just as you’d expect from an instance property.
Given this, and returning to FixedWidthInteger
, I think it would have made more sense if the type property .bitWidth
had been called .bitCount
and the instance property .bitWidth
had been the “The minimum number of bits required to represent the value in binary form”.