How to Copy Certain Bytes of a Date Type in Swift

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 want to do the same thing in Swift, and in this case instead of being type byte [], it is of type Data.

What I tried to do was the following:

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

    
asked by anonymous 21.06.2017 / 17:16

1 answer

1

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]
    
22.06.2017 / 21:11