Swift: Java equivalent of Arrays.copyOfRange for [UInt8]












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










share|improve this question
























  • Don't add the answer to your question. You can post your solution as an answer, or accept one of the existing answers.
    – Martin R
    Nov 12 '18 at 12:51










  • Ok edited......
    – Mickael Belhassen
    Nov 12 '18 at 12:53
















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










share|improve this question
























  • Don't add the answer to your question. You can post your solution as an answer, or accept one of the existing answers.
    – Martin R
    Nov 12 '18 at 12:51










  • Ok edited......
    – Mickael Belhassen
    Nov 12 '18 at 12:53














0












0








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










share|improve this question















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







swift






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 12 '18 at 12:52







Mickael Belhassen

















asked Nov 12 '18 at 12:01









Mickael BelhassenMickael Belhassen

1719




1719












  • Don't add the answer to your question. You can post your solution as an answer, or accept one of the existing answers.
    – Martin R
    Nov 12 '18 at 12:51










  • Ok edited......
    – Mickael Belhassen
    Nov 12 '18 at 12:53


















  • Don't add the answer to your question. You can post your solution as an answer, or accept one of the existing answers.
    – Martin R
    Nov 12 '18 at 12:51










  • Ok edited......
    – Mickael Belhassen
    Nov 12 '18 at 12:53
















Don't add the answer to your question. You can post your solution as an answer, or accept one of the existing answers.
– Martin R
Nov 12 '18 at 12:51




Don't add the answer to your question. You can post your solution as an answer, or accept one of the existing answers.
– Martin R
Nov 12 '18 at 12:51












Ok edited......
– Mickael Belhassen
Nov 12 '18 at 12:53




Ok edited......
– Mickael Belhassen
Nov 12 '18 at 12:53












4 Answers
4






active

oldest

votes


















1














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





share|improve this answer































    0














    This should definitfly work:



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





    share|improve this answer

















    • 1




      This answer could be much more helpful if you explain why it is correct ad relate it to the specifics of the question.
      – Dragonthoughts
      Nov 12 '18 at 12:30



















    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
    }

    }





    share|improve this answer



















    • 1




      Did you check your code before posting? This does not compile.
      – Martin R
      Nov 12 '18 at 12:06










    • I was just about to press "Post Your Answer" when I saw yours come up. Mine was essentially the same. The key part to this answer is the range subscript arr[from...to] which is essentially doing the equivalent of copyOfRange. (Except that in Swift you can also use this syntax to write to a subset of the array as well as to extract it.)
      – Steven W. Klassen
      Nov 12 '18 at 12:08










    • @MartinR hand write it
      – Sh_Khan
      Nov 12 '18 at 12:09












    • Thanks for your quick answer, I want to give it a byteArray so I just have to replace Int by UInt8?
      – Mickael Belhassen
      Nov 12 '18 at 12:11










    • @MickaelBelhassen yeah
      – Shubham Bakshi
      Nov 12 '18 at 12:12



















    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
    }





    share|improve this answer





















      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53261757%2fswift-java-equivalent-of-arrays-copyofrange-for-uint8%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














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





      share|improve this answer




























        1














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





        share|improve this answer


























          1












          1








          1






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





          share|improve this answer














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






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 12 '18 at 14:30

























          answered Nov 12 '18 at 12:57









          vacawamavacawama

          95.8k13172197




          95.8k13172197

























              0














              This should definitfly work:



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





              share|improve this answer

















              • 1




                This answer could be much more helpful if you explain why it is correct ad relate it to the specifics of the question.
                – Dragonthoughts
                Nov 12 '18 at 12:30
















              0














              This should definitfly work:



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





              share|improve this answer

















              • 1




                This answer could be much more helpful if you explain why it is correct ad relate it to the specifics of the question.
                – Dragonthoughts
                Nov 12 '18 at 12:30














              0












              0








              0






              This should definitfly work:



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





              share|improve this answer












              This should definitfly work:



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






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Nov 12 '18 at 12:15









              JonathanJonathan

              1




              1








              • 1




                This answer could be much more helpful if you explain why it is correct ad relate it to the specifics of the question.
                – Dragonthoughts
                Nov 12 '18 at 12:30














              • 1




                This answer could be much more helpful if you explain why it is correct ad relate it to the specifics of the question.
                – Dragonthoughts
                Nov 12 '18 at 12:30








              1




              1




              This answer could be much more helpful if you explain why it is correct ad relate it to the specifics of the question.
              – Dragonthoughts
              Nov 12 '18 at 12:30




              This answer could be much more helpful if you explain why it is correct ad relate it to the specifics of the question.
              – Dragonthoughts
              Nov 12 '18 at 12:30











              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
              }

              }





              share|improve this answer



















              • 1




                Did you check your code before posting? This does not compile.
                – Martin R
                Nov 12 '18 at 12:06










              • I was just about to press "Post Your Answer" when I saw yours come up. Mine was essentially the same. The key part to this answer is the range subscript arr[from...to] which is essentially doing the equivalent of copyOfRange. (Except that in Swift you can also use this syntax to write to a subset of the array as well as to extract it.)
                – Steven W. Klassen
                Nov 12 '18 at 12:08










              • @MartinR hand write it
                – Sh_Khan
                Nov 12 '18 at 12:09












              • Thanks for your quick answer, I want to give it a byteArray so I just have to replace Int by UInt8?
                – Mickael Belhassen
                Nov 12 '18 at 12:11










              • @MickaelBelhassen yeah
                – Shubham Bakshi
                Nov 12 '18 at 12:12
















              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
              }

              }





              share|improve this answer



















              • 1




                Did you check your code before posting? This does not compile.
                – Martin R
                Nov 12 '18 at 12:06










              • I was just about to press "Post Your Answer" when I saw yours come up. Mine was essentially the same. The key part to this answer is the range subscript arr[from...to] which is essentially doing the equivalent of copyOfRange. (Except that in Swift you can also use this syntax to write to a subset of the array as well as to extract it.)
                – Steven W. Klassen
                Nov 12 '18 at 12:08










              • @MartinR hand write it
                – Sh_Khan
                Nov 12 '18 at 12:09












              • Thanks for your quick answer, I want to give it a byteArray so I just have to replace Int by UInt8?
                – Mickael Belhassen
                Nov 12 '18 at 12:11










              • @MickaelBelhassen yeah
                – Shubham Bakshi
                Nov 12 '18 at 12:12














              0












              0








              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
              }

              }





              share|improve this answer














              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
              }

              }






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Nov 12 '18 at 12:22

























              answered Nov 12 '18 at 12:05









              Sh_KhanSh_Khan

              40.1k51125




              40.1k51125








              • 1




                Did you check your code before posting? This does not compile.
                – Martin R
                Nov 12 '18 at 12:06










              • I was just about to press "Post Your Answer" when I saw yours come up. Mine was essentially the same. The key part to this answer is the range subscript arr[from...to] which is essentially doing the equivalent of copyOfRange. (Except that in Swift you can also use this syntax to write to a subset of the array as well as to extract it.)
                – Steven W. Klassen
                Nov 12 '18 at 12:08










              • @MartinR hand write it
                – Sh_Khan
                Nov 12 '18 at 12:09












              • Thanks for your quick answer, I want to give it a byteArray so I just have to replace Int by UInt8?
                – Mickael Belhassen
                Nov 12 '18 at 12:11










              • @MickaelBelhassen yeah
                – Shubham Bakshi
                Nov 12 '18 at 12:12














              • 1




                Did you check your code before posting? This does not compile.
                – Martin R
                Nov 12 '18 at 12:06










              • I was just about to press "Post Your Answer" when I saw yours come up. Mine was essentially the same. The key part to this answer is the range subscript arr[from...to] which is essentially doing the equivalent of copyOfRange. (Except that in Swift you can also use this syntax to write to a subset of the array as well as to extract it.)
                – Steven W. Klassen
                Nov 12 '18 at 12:08










              • @MartinR hand write it
                – Sh_Khan
                Nov 12 '18 at 12:09












              • Thanks for your quick answer, I want to give it a byteArray so I just have to replace Int by UInt8?
                – Mickael Belhassen
                Nov 12 '18 at 12:11










              • @MickaelBelhassen yeah
                – Shubham Bakshi
                Nov 12 '18 at 12:12








              1




              1




              Did you check your code before posting? This does not compile.
              – Martin R
              Nov 12 '18 at 12:06




              Did you check your code before posting? This does not compile.
              – Martin R
              Nov 12 '18 at 12:06












              I was just about to press "Post Your Answer" when I saw yours come up. Mine was essentially the same. The key part to this answer is the range subscript arr[from...to] which is essentially doing the equivalent of copyOfRange. (Except that in Swift you can also use this syntax to write to a subset of the array as well as to extract it.)
              – Steven W. Klassen
              Nov 12 '18 at 12:08




              I was just about to press "Post Your Answer" when I saw yours come up. Mine was essentially the same. The key part to this answer is the range subscript arr[from...to] which is essentially doing the equivalent of copyOfRange. (Except that in Swift you can also use this syntax to write to a subset of the array as well as to extract it.)
              – Steven W. Klassen
              Nov 12 '18 at 12:08












              @MartinR hand write it
              – Sh_Khan
              Nov 12 '18 at 12:09






              @MartinR hand write it
              – Sh_Khan
              Nov 12 '18 at 12:09














              Thanks for your quick answer, I want to give it a byteArray so I just have to replace Int by UInt8?
              – Mickael Belhassen
              Nov 12 '18 at 12:11




              Thanks for your quick answer, I want to give it a byteArray so I just have to replace Int by UInt8?
              – Mickael Belhassen
              Nov 12 '18 at 12:11












              @MickaelBelhassen yeah
              – Shubham Bakshi
              Nov 12 '18 at 12:12




              @MickaelBelhassen yeah
              – Shubham Bakshi
              Nov 12 '18 at 12:12











              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
              }





              share|improve this answer


























                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
                }





                share|improve this answer
























                  0












                  0








                  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
                  }





                  share|improve this answer












                  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
                  }






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 12 '18 at 12:53









                  Mickael BelhassenMickael Belhassen

                  1719




                  1719






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53261757%2fswift-java-equivalent-of-arrays-copyofrange-for-uint8%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Coverage of Google Street View

                      Full-time equivalent

                      Surfing