[swift-evolution] Shift operator: the type of the second operand

Jeremy Pereira jeremy.j.pereira at googlemail.com
Fri Dec 18 05:55:38 CST 2015


These are the definitions of the right shift operators

	public func >>(lhs: Int8, rhs: Int8) -> Int8

	public func >>(lhs: Int, rhs: Int) -> Int

	public func >>(lhs: UInt, rhs: UInt) -> UInt

	public func >>(lhs: Int64, rhs: Int64) -> Int64

	public func >>(lhs: UInt64, rhs: UInt64) -> UInt64

	public func >>(lhs: UInt8, rhs: UInt8) -> UInt8

	public func >>(lhs: UInt16, rhs: UInt16) -> UInt16

	public func >>(lhs: Int16, rhs: Int16) -> Int16

	public func >>(lhs: Int32, rhs: Int32) -> Int32

	public func >>(lhs: UInt32, rhs: UInt32) -> UInt32


Note that both left and right hand side are of the same type. In my opinion, rhs, which represents the number of bits to shift, should always be an Int e.g.

	public func >>(lhs: UInt64, rhs: Int) -> UInt64

The two operands are fundamentally different, the left hand one is conceptually an array of bits and the right hand one is conceptually a count. 

The current definitions mean that I almost always have to do a cast on the right operand with shift operations. e.g. the following snippet that converts a UInt64 into an array of boolean values.

    let aNumber: UInt64 = 0x123456
    var numberAsBits: [Bool] = [];
    for i in 0 ..< 64
    {
        numberAsBits.append((aNumber >> i) & 1 != 0); // Error because i needs to be cast to a UInt64
    }

I would like additional versions of the shift operator where rhs is an Int please.

Needless to say, the same applies to the left shift operators.



More information about the swift-evolution mailing list