gpt4 book ai didi

arrays - 在 Swift 中,获取数组中最后两项的最简洁方法是什么?

转载 作者:IT王子 更新时间:2023-10-29 05:08:45 25 4
gpt4 key购买 nike

在 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", "dos", "tres"]
print myList[-2:] # ["dos", "tres"]

最佳答案

在 Swift 5 中,根据您的需要,您可以选择以下模式之一,以便从数组的最后两个元素中获取一个新数组。


#1。使用数组的 suffix(_:)

在 Swift 中,符合 Collection 协议(protocol)的对象有一个 suffix(_:) 方法。数组的 suffix(_:)有以下声明:

func suffix(_ maxLength: Int) -> ArraySlice<Element>

Returns a subsequence, up to the given maximum length, containing the final elements of the collection.

用法:

let array = [1, 2, 3, 4]
let arraySlice = array.suffix(2)
let newArray = Array(arraySlice)
print(newArray) // prints: [3, 4]

#2。使用 Arraysubscript(_:)

作为suffix(_:) 方法的替代方法,您可以使用Arraysubscript(_:)。下标:

let array = [1, 2, 3, 4]
let range = array.index(array.endIndex, offsetBy: -2) ..< array.endIndex
//let range = array.index(array.endIndex, offsetBy: -2)... // also works
let arraySlice = array[range]
let newArray = Array(arraySlice)
print(newArray) // prints: [3, 4]

关于arrays - 在 Swift 中,获取数组中最后两项的最简洁方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31007643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com