index(_:offsetBy:limitedBy)...what's the type?

I'm trying to get a simple index offset:


func foo<Bytes: Collection>(data: Bytes) where Bytes.Element == UInt8 {
    let nextFrameStartIndex = data.index(data.startIndex, offsetBy: 10, limitedBy: data.endIndex)
}


If I put the integer literal 10 there it compiles just fine. If I instead create a variable of type Int and pass that I get a compiler error:


"Cannot invoke 'index' with an argument list of type '(Bytes.Index, offsetBy: Int, limitedBy: Bytes.index)'

Accepted Reply

When an associated type is declared with `=`, the right hand side represents a default type for the associated type.

I'm not sure when exactly the `default` would be applied, so I cannot explain why your literal case works as expected.


But, generally, when you implement something with associated types, you should better explicitly specify them:

func foo<Bytes: Collection>(data: Bytes)
    where Bytes.Element == UInt8, Bytes.IndexDistance == Int
{
    let nextFrameStartIndex = data.index(data.startIndex, offsetBy: index, limitedBy: data.endIndex)
}

(Assume `index` is a variable of `Int`.)

Replies

I cannot find the thread where a similar bquestiçon was addressed.


I think I remember type to declare is not Int but another type of Integer (which, I can't remember).

Maybe FixedWidthInteger ?

Well, the header file declares it as Self.IndexDistance, and when I scroll up to the top of the collection protocol it has


associatedtype IndexDistance = Int


So you can see why I'm so confused 🙂

When an associated type is declared with `=`, the right hand side represents a default type for the associated type.

I'm not sure when exactly the `default` would be applied, so I cannot explain why your literal case works as expected.


But, generally, when you implement something with associated types, you should better explicitly specify them:

func foo<Bytes: Collection>(data: Bytes)
    where Bytes.Element == UInt8, Bytes.IndexDistance == Int
{
    let nextFrameStartIndex = data.index(data.startIndex, offsetBy: index, limitedBy: data.endIndex)
}

(Assume `index` is a variable of `Int`.)

Thank you! That never even occurred to me to try.