加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

数组 – 在Swift中,最简单的方法是在Array中获取最后两个项目?

发布时间:2020-12-14 05:20:21 所属栏目:百科 来源:网络整理
导读:有没有更清洁的方式来获取 Swift中最后两个数组的项目?一般来说,我尝试避免使用这种方法,因为它很容易被一个一个的索引. (在这个例子中使用Swift 1.2) // Swift -- slices are kind of a hassle?let oneArray = ["uno"]let twoArray = ["uno","dos"]let thr
有没有更清洁的方式来获取 Swift中最后两个数组的项目?一般来说,我尝试避免使用这种方法,因为它很容易被一个一个的索引. (在这个例子中使用Swift 1.2)
// Swift -- slices are kind of a hassle?
let oneArray = ["uno"]
let twoArray = ["uno","dos"]
let threeArray = ["uno","dos","tres"]

func getLastTwo(array: [String]) -> [String] {
    if array.count <= 1 {
        return array
    } else {
        let slice: ArraySlice<String> = array[array.endIndex-2..<array.endIndex]
        var lastTwo: Array<String> = Array(slice)
        return lastTwo
    }
}

getLastTwo(oneArray)   // ["uno"]
getLastTwo(twoArray)   // ["uno","dos"]
getLastTwo(threeArray) // ["dos","tres"]

我希望更接近Python的方便.

## Python -- very convenient slices
myList = ["uno","tres"]
print myList[-2:] # ["dos","tres"]

myList[-2:]

是的,我有一个增强请求,要求负号索引符号,我建议你也提交一个.

但是,你不应该使自己比你更难.内置的全局后缀功能完全符合您的要求:

let oneArray = ["uno"]
let twoArray = ["uno","tres"]

let arr1 = suffix(oneArray,2) // ["uno"]
let arr2 = suffix(twoArray,2) // ["uno","dos"]
let arr3 = suffix(threeArray,2) // ["dos","tres"]

结果是一个切片,但如果需要,您可以将其强制转换为数组.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读