简体   繁体   中英

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.

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]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM