I would like to make CountableClosedRange
conform to the ExpressibleByIntegerLiteral
protocol so that I can create "single integer ranges" (see my other question). The goal is to be able to assign integer literals to variables of type CountableClosedRange
so that the following would be valid code:
var range = 5...10 // Infers the type of range to be CountableClosedRange
range = 8 // Interprets the integer literal as a CountableClosedRange
So I created an extension to add the protocol conformance:
extension CountableClosedRange: ExpressibleByIntegerLiteral {
public init(integerLiteral value: IntegerLiteralType) {
self = value...value
}
}
Unfortunately this code does not compile. The line self = value...value
throws the following error:
Cannot assign value of type 'CountableClosedRange<IntegerLiteralType>' (aka 'CountableClosedRange<Int>') to type 'CountableClosedRange<_>'
The problem seems to be the generic nature of CountableClosedRange
: It's defined as
struct CountableClosedRange<Bound> : RandomAccessCollection where Bound : Comparable, Bound : _Strideable, Bound.Stride : SignedInteger
Inside my extension the generic type Bound
is not specified whereas IntegerLiteralType
is specified (it's an Int
). So I tried to specify Bound
like this:
extension CountableClosedRange: ExpressibleByIntegerLiteral where Bound == Int { ... }
but then I got another compiler error:
Extension of type 'CountableClosedRange' with constraints cannot have an inheritance clause