0

I am translating a java code to swift, and I want to know what is the equivalent for swift of Arrays.copyOfRange:

public static byte[] copyOfRange(byte[] original, int from, int to) 

for my example I want to translate the next line:

Arrays.copyOfRange(packet.value(), 2, packet.length())

Thanks

Mickael Belhassen
  • 2,970
  • 1
  • 25
  • 46

4 Answers4

4

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]
}
vacawama
  • 150,663
  • 30
  • 266
  • 294
0

You can try

func getRange (arr:[Int],from:Int,to:Int) -> [Int]? {

  if from >= 0 && from < arr.count && to >= 0 && to < arr.count && from < to {

     return Array(arr[from...to])
  }

 return nil
}

May write

extension Array  {

    func getRenage (from:Int,to:Int) -> [Element]? {

        if from >= 0 && from < self.count && to >= 0 && to < self.count && from < to {

            return Array(self[from...to])
        }

        return nil
    }

}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
0

This should definitfly work:

    var array = [1,2,3,4,5,6,7,8,9]
    var partOfArray = array[5...8]
    print(partOfArray)
0

Answer

    func getRange(arr: [UInt8], from: Int, to: Int) -> [UInt8]? {

    if from >= 0 && to >= from && to <= arr.count{

        return Array(arr[from..<to])
    }

    return nil
}
Mickael Belhassen
  • 2,970
  • 1
  • 25
  • 46