如何从字节数组([UInt8])获取字节(UInt8)?

时间:2016-09-15 08:34:42

标签: swift byte uint8t uint8array

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

如果将偏移更改为任何其他Int将导致相同的错误。但是如果我使用bytes [0]则没有问题。可能是因为Swift知道期望什么类型并相应地转换0。我想知道那是什么类型。

1 个答案:

答案 0 :(得分:1)

数组是由Int索引的集合:

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

在你的情况下:

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