如何从字节数组 ([UInt8]) 中获取一个字节 (UInt8)?
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'
}
如果将偏移量更改为任何其他 Int 将导致相同的错误。但是,如果我使用 bytes[0] 就没有问题。可能是因为 Swift 知道期望的类型并相应地转换 0 。我想知道那是什么类型。
数组是由 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]
}
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 。我想知道那是什么类型。
数组是由 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]
}