The problem is that you are trying to force newNumbers to be of type Data
but the result of the subscript is of type MutableRangeReplaceableRandomAccessSlice
. Just initialize a new Data object with this object:
let string = "0123456789"
let stringData = Data(string.utf8)
let subdata = Data(stringData[1...3])
print(Array(subdata)) // "[49, 50, 51]
Another option is to use the subdata(in range: Range<Data.Index>) -> Data
method that returns an object of type Data, but you must pass half-open range
instead of countable closed range. (eg, ..<
instead of ...
)
let string = "0123456789"
let stringData = Data(string.utf8)
let subdata = stringData.subdata(in: 1..<4)
print(Array(subdata)) // "[49, 50, 51]