0
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.

3
  • 1
    offset: Int should work. Commented Sep 15, 2016 at 8:38
  • or return bytes[Int(offset)] Commented Sep 15, 2016 at 8:41
  • Martin R that was the only thing I haven't tried. UInt didn't work either. Could you post it as an answer so I can mark it? Commented Sep 15, 2016 at 8:44

1 Answer 1

1

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]
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.