How to copy end of the Array in swift?

后端 未结 6 1729
感动是毒
感动是毒 2020-11-30 15:20

There must be some really elegant way of copying end of the Array using Swift starting from some index, but I just could not find it, so I ended with this:

f         


        
相关标签:
6条回答
  • 2020-11-30 15:54

    This is one possible solution, there are probably a few more

    let array = [1, 2, 3, 4, 5]
    let endOfArray = Array(array[2..<array.endIndex]) // [3, 4, 5]
    

    Or with dynamic index and range check

    let array = [1, 2, 3, 4, 5]
    let index = 2
    let endOfArray : [Int]
    if index < array.count {
      endOfArray = Array(array[index..<array.endIndex]) // [3, 4, 5]
    } else {
      endOfArray = array
    }
    

    The re-initializition of the array is needed since the range subscription of Array returns ArraySlice<Element>

    0 讨论(0)
  • 2020-11-30 15:55

    You could use filter

    func getEndOfArray( arr : [Int], fromIndex : Int? = 0) -> [Int] {
        let filteredArray = arr.filter({$0 <= fromIndex})
    
        return filteredArray
    }
    

    took the liberty of changing to [Int] for the sake of this example.

    0 讨论(0)
  • 2020-11-30 16:03

    You can use suffix:

    let array = [1,2,3,4,5,6]
    let lastTwo = array.suffix(2) // [5, 6]
    

    As mentioned in the comment: This gives you an ArraySlice object which is sufficient for most cases. If you really need an Array object you have to cast it:

    let lastTwoArray = Array(lastTwo)
    
    0 讨论(0)
  • 2020-11-30 16:06

    You can subscript an open ended range now. This will include elements starting at index 5.

    Swift 4.2

    array[5...]
    
    0 讨论(0)
  • 2020-11-30 16:09

    You could use the new method removeFirst(_:) in Swift 4

    var array = [1, 2, 3, 4, 5]
    array.removeFirst(2)
    print(array) // [3, 4, 5]
    
    0 讨论(0)
  • 2020-11-30 16:16

    And another one ...

    let array = [1, 2, 3, 4, 5]
    let fromIndex = 2
    let endOfArray = array.dropFirst(fromIndex)
    print(endOfArray) // [3, 4, 5]
    

    This gives an ArraySlice which should be good enough for most purposes. If you need a real Array, use

    let endOfArray = Array(array.dropFirst(fromIndex))
    

    An empty array/slice is created if the start index is larger than (or equal to) the element count.

    0 讨论(0)
提交回复
热议问题