Swift:Java等效于[UInt8]的Arrays.copyOfRange

时间:2018-11-12 12:01:17

标签: swift

我正在将Java代码转换为swift,我想知道什么是Swift的Arrays.copyOfRange等效项:

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

对于我的示例,我想翻译下一行:

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

谢谢

4 个答案:

答案 0 :(得分:1)

答案

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

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

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

    return nil
}

答案 1 :(得分:1)

如果上限值大于数组长度,则Java的copyOfRange还将用零填充结果数组。此功能也可以处理这种情况。

可以将此功能设为通用。它适用于ExpressibleByIntegerLiteral填充所需的任何符合0的类型。

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)
}

示例:

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]
}

答案 2 :(得分:0)

您可以尝试

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
}

可以写

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
    }

}

答案 3 :(得分:0)

这应该definitfly工作:

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