HungCLo HungCLo - 6 months ago 113
Swift Question

How to implement java Arraycopy in Swift?

The definition of Java's

arraycopy
is here:
Java arraycopy

My Java code is below:

public byte[] getRawData() {
byte[] raw = new byte[value.length + 4];
//little endian defined by fido spec
raw[0] = (byte) (tag);
raw[1] = (byte) (tag>>8);
raw[2] = (byte) (len);
raw[3] = (byte) (len>>8);
System.arraycopy(value, 0, raw, 4, value.length);
return raw;
}


Here is my Swift code:

public func getRawData() -> [UInt8] {
var raw = [UInt8(value.count + 4)]
raw[0] = UInt8(tag)
raw[1] = UInt8(tag>>8)
raw[2] = UInt8(len)
raw[3] = UInt8(len>>8)
// The place the put swift arraycopy
return raw

}


There is no similar function to
arraycopy
in Swift. How can I properly reimplement this function?

Answer

You could use Swift's slice to achieve the same results as Java's arraycopy:

var src = [0, 1, 2, 3]
var dst = [4, 5, 6, 7, 8, 9]

dst[1...4] = src[0...3]

print(dst) // [4, 0, 1, 2, 3, 9]

Note: This does not handle bounds checking.