如何从字节数组([UInt8])获取一个字节(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'
}
如果你改变了偏移到任何其他诠释会导致同样的错误。但是,如果我使用字节[0]没有问题。可能因为Swift知道期望的类型并相应地转换0。我想知道是什么类型。如何从字节数组([UInt8])获取一个字节(UInt8)?
答
阵列由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]
}
'偏移:Int'应该工作。 –
或'返回字节[Int(offset)]' –
Martin R是我唯一没有尝试过的东西。 UInt也没有工作。你可以把它作为答案发布,以便我可以标记它吗? – Mark