Java's copyOfRange
will also pad the resulting array with zeroes if the upper range value is greater than the array length. This function handles that case as well.
This function can be made generic. It works for any type that conforms to ExpressibleByIntegerLiteral
which is needed for the 0
padding.
func copyOfRange<T>(arr: [T], from: Int, to: Int) -> [T]? where T: ExpressibleByIntegerLiteral {
guard from >= 0 && from <= arr.count && from <= to else { return nil }
var to = to
var padding = 0
if to > arr.count {
padding = to - arr.count
to = arr.count
}
return Array(arr[from..<to]) + [T](repeating: 0, count: padding)
}
Examples:
let arr: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
if let result = copyOfRange(arr: arr, from: 0, to: 3) {
print(result) // [0, 1, 2]
}
if let result = copyOfRange(arr: arr, from: 7, to: 12) {
print(result) // [7, 8, 9, 0, 0]
}