如何快速复制数组的结尾? [英] How to copy end of the Array in swift?

查看:22
本文介绍了如何快速复制数组的结尾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一定有一些非常优雅的方式使用 Swift 从某个索引开始复制数组的结尾,但我找不到它,所以我以这个结束:

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:

func getEndOfArray<T>( arr : [T], fromIndex : Int? = 0) -> [T] {
    var i=0;
    var newArray : [T] = [T]()
    for item in arr {
        if i >= fromIndex {
            newArray.append(item)
        }
        i = i + 1;
    }
    return newArray // returns copy of the array starting from index fromIndex
}

在没有额外功能的情况下,有没有更好的方法来做到这一点?

Is there a better way of doing this without extra function?

推荐答案

还有一个...

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

这给出了一个 ArraySlice 对于大多数人来说应该足够好目的.如果你需要一个真正的Array,使用

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.

这篇关于如何快速复制数组的结尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆