有没有更清洁的方式来获取
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"]@H_403_3@我希望更接近Python的方便.
## Python -- very convenient slices myList = ["uno","tres"] print myList[-2:] # ["dos","tres"]
@H_403_3@myList[-2:]
@H_403_3@是的,我有一个增强请求,要求负号索引符号,我建议你也提交一个.
@H_403_3@但是,你不应该使自己比你更难.内置的全局后缀功能完全符合您的要求:
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"]@H_403_3@结果是一个切片,但如果需要,您可以将其强制转换为数组.