[swift-evolution] Bitshift operators

Ben Rimmington me at benrimmington.com
Thu Jun 16 06:25:47 CDT 2016


Brent Royal-Gordon wrote:

> While I was watching WWDC videos today, I noticed that there's
> a bit of annoying boilerplate in OptionSet specifications, and
> set out to get rid of it. Basically, what I'd like to do is this:
>
> 	extension OptionSet where RawValue: Integer {
> 	    init(bit bits: RawValue...) {
> 	        self.init(rawValue: bits.reduce(0) { $0 | (1 << $1) })
> 	    }
> 	}
>
> 	struct FooOptions: OptionSet {
> 	    let rawValue: Int
>
> 	    static let bar = FooOptions(bit: 0)
> 	    static let baz = FooOptions(bit: 1)
> 	}
>
> However, this was thwarted by the fact that the << operator is
> not in Integer. Or BitwiseOperations. Or any protocol, in fact.

Alternatively, using binary integer literals:

	struct FooOptions: OptionSet {
	    let rawValue: Int

	    static let bar = Self(rawValue: 0b01)
	    static let baz = Self(rawValue: 0b10)
	}

Does the revised SE-0068 proposal allow this?

-- Ben




More information about the swift-evolution mailing list