2

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


Is there any way to make this work?

Mischa
  • 15,816
  • 8
  • 59
  • 117
  • 1
    I think you can't before https://github.com/apple/swift-evolution/blob/master/proposals/0143-conditional-conformances.md is implemented, compare https://stackoverflow.com/questions/44584237/swift-extension-on-generic-struct-based-on-properties-of-type-t for a similar issue. – Martin R Aug 12 '17 at 14:37

0 Answers0