Indexing into arrays is only possible using the Int type.
As Int is 64-bit, you would assume that indexing into an array would also work using UInt8 for example, as it is only 8 bit. But there will be a compiler error.
This is expected, as the Array struct defines subscripting as:
subscript (index: Int) -> T
I assume that smart people have thought about this, and the decision to make this index an Int has good reasons.
But why not allow indexing via 'UnsignedIntegerType' for example? This would allow for indexing into an array using
any of the Integer-types and then there is not need to create separate Ints via Int(UInt16-value).
Can anyone elaborate?
Code examples of errors and how to fix/workaround them:
// the count is larger then what can be represented by UInt8
var int8Array : [UInt8] = [UInt8](count: 2^12, repeatedValue: 0)
let index8 : UInt8 = 12
let valueAtIndex8 = int8Array[index8]
// >> error: 'Cannot subscript a value of type '[UInt8]' with an index of type 'UInt8'
let index16 : UInt16 = 12
let valueAtIndex16 : UInt8 = int8Array[index16]
// >> error: 'Cannot subscript a value of type '[UInt8]' with an index of type 'UInt16'
let index64 : UInt64 = 12
let valueAtIndex64 = int8Array[index64]
// >> error: 'Cannot subscript a value of type '[UInt8]' with an index of type 'UInt64'
// No error here, but an extra operation is needed
let index16AsInt : Int = Int(index16)
let valueAtIndex16AsInt = int8Array[index16AsInt]
// No error here
let indexInt : Int = 12 // A 64-bit signed integer value type
let valueAtIndexInt : UInt8 = int8Array[indexInt]