How to copy certain Bytes of a Date type in Swift

Asked

Viewed 41 times

0

As an example I android to do what you want to use the following:

byte[] byte = ....;
byte[] resultado = Arrays.copyOfRange(byte, 1,3);

And I intend to do the same but on Swift being that in this case instead of the byte type[] is the Data type.

What I tried to do was this:

let newNumbers:Data = dataBytes[1...3]

but gives the following error "Cannot subscript a value of type 'Data' with an index of type 'Countableclosedrange'", some can help me here?

1 answer

1

The problem is that Voce is trying to force newNumbers to be of the type Data but the result of the subscript is of the type MutableRangeReplaceableRandomAccessSlice. Simply Voce initialize a new Date object with that 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 method subdata(in range: Range<Data.Index>) -> Data which returns an object of type Data, but Voce needs to pass a half-open range instead of countable closed range. (ex.: ..< instead of ...)

let string = "0123456789"
let stringData = Data(string.utf8)
let subdata = stringData.subdata(in: 1..<4)
print(Array(subdata))  // "[49, 50, 51]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.