How to copy end of the Array in swift?

后端 未结 6 1743
感动是毒
感动是毒 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 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)
    

提交回复
热议问题