Search code examples
swiftsubscriptuint8array

Subscript range of [UInt8] - Swift


So the issue I'm having is that I have an object with a argument in the init() that requires an [UInt8]. I want to be able to grab a range from another array and use that in the init. See example.

class Test {

    init(fromArray: [UInt8]) {
    // performs work
    }
}

let myStockArray: [UInt8] = [1,2,3,4,5,6,7,8] // reference array

let test = Test(fromArray: myStockArray[1...4]) // doesn't work

How can I get this to work? The error I get is: Cannot subscript a value of type '[UInt8]' with an index of type 'CountableClosedRange'


Solution

  • Subscripting an array with a range doesn't return an array and this is the main issue. You are trying to setArraySlice<UInt8> type data to the constructor that have inside [UInt8] type.

    Try this approach:

    class Test {
    
        init(fromArray: [UInt8]) {
            // performs work
        }
    }
    
    let myStockArray: [UInt8] = [1,2,3,4,5,6,7,8] // reference array
    
    let test = Test(fromArray: Array(myStockArray[1...4]))