Search code examples
swiftbyteuint8tuint8array

How to get a byte (UInt8) from an array of bytes ([UInt8])?


func readByte(bytes: [UInt8], offset: UInt8) -> UInt8 {
    return bytes[offset] // Error: Cannot subscript a value of type '[UInt8]' with an index of type 'UInt8'
}

If you change the offset to any other Int will result in the same error. However if I use bytes[0] there is no problem. Probably because Swift knows what type to expect and converts the 0 accordingly. I am wondering what type that is.


Solution

  • Arrays are collections indexed by Int:

    public struct Array<Element> : RandomAccessCollection, MutableCollection {
        // ...
        public typealias Index = Int
        // ...
        public subscript(index: Int) -> Element
        // ...
    }
    

    In your case:

    func readByte(bytes: [UInt8], offset: Int) -> UInt8 {
        return bytes[offset]
    }