我想在 Swift 中的 CollectionType 上编写一个扩展,它将在数组中的一个对象之后找到 x 个对象。显然它需要被保护才能工作,即使在该项目之后没有任何物体。
在我的脑海里签名是这样的:
func itemsAfterItem(item: T, limit: Int?) -> [T]
虽然我不知道如何实现它,有人可以帮忙吗?
最佳答案
任意集合的可能实现
Equatable
元素(内联解释)。主要的
挑战在于获得正确的参数类型和约束。
extension CollectionType where Generator.Element: Equatable,
SubSequence.Generator.Element == Generator.Element {
func itemsAfterItem(item: Generator.Element, limit: Index.Distance?) -> [Generator.Element] {
if let idx = indexOf(item) where idx != endIndex {
// Start after the given item:
let from = idx.advancedBy(1)
// Up to min(from + limit, endIndex):
let to = limit.map { from.advancedBy($0, limit: endIndex) } ?? endIndex
// Return slice as an array:
return Array(self[from..<to])
} else {
// Item not found, or only at the last position.
return []
}
}
}
理解
let to = limit.map { from.advancedBy($0, limit: endIndex) } ?? endIndex
部分留给读者作为练习:)
例子:
[1, 2, 3, 4, 5, 6].itemsAfterItem(2, limit: 2) // [3, 4]
["x", "y", "z"].itemsAfterItem("y", limit: 4) // ["z"]
[1, 2, 3].itemsAfterItem(7, limit: 4) // []
[1.1, 2.2, 3.3].itemsAfterItem(1.1, limit: nil) // [2.2, 3.3]
非数组集合的示例:
"abcdef".characters.itemsAfterItem("b", limit: 2) // ["c", "d"]
关于swift - Swift 中集合类型的扩展,用于查找对象之后的所有对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38918023/