在Swift中,是否有一种聪明的方法来使用数组上的高阶方法来返回5个第一个对象? obj-c的方法是保存一个索引,而for-loop则通过数组将索引值递增到5,然后返回新的数组。有办法做到这一点与过滤器,映射或减少?
当前回答
对于对象数组,您可以从Sequence创建一个扩展。
extension Sequence {
func limit(_ max: Int) -> [Element] {
return self.enumerated()
.filter { $0.offset < max }
.map { $0.element }
}
}
用法:
struct Apple {}
let apples: [Apple] = [Apple(), Apple(), Apple()]
let limitTwoApples = apples.limit(2)
// limitTwoApples: [Apple(), Apple()]
其他回答
let a: [Int] = [0, 0, 1, 1, 2, 2, 3, 3, 4]
let b: [Int] = Array(a.prefix(5))
// result is [0, 0, 1, 1, 2]
你可以很容易地做到这一点,不需要filter, map, reduce或prefix,只需要通过下标返回数组的一个范围:
var wholeArray = [1, 2, 3, 4, 5, 6]
var n = 5
var firstFiveSlice = wholeArray[0..<n] // 1,2,3,4,5
let firstFiveArray = Array(firstFiveSlice)
Swift 4保存数组类型
extension Array {
func take(_ elementsCount: Int) -> [Element] {
let min = Swift.min(elementsCount, count)
return Array(self[0..<min])
}
}
简单明了
extension Array {
func first(elementCount: Int) -> Array {
let min = Swift.min(elementCount, count)
return Array(self[0..<min])
}
}
对于对象数组,您可以从Sequence创建一个扩展。
extension Sequence {
func limit(_ max: Int) -> [Element] {
return self.enumerated()
.filter { $0.offset < max }
.map { $0.element }
}
}
用法:
struct Apple {}
let apples: [Apple] = [Apple(), Apple(), Apple()]
let limitTwoApples = apples.limit(2)
// limitTwoApples: [Apple(), Apple()]