swift - Swift 中集合类型的扩展,用于查找对象之后的所有对象

标签 swift generics collections functional-programming

我想在 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/

相关文章:

collections - 如何在我的 YAML Swagger 定义中将属性类型定义为字符串列表(列表、集合、数组、集合)

ios - 使用 Firebase 添加好友系统的最佳实践?

c# - 无法在泛型方法中隐式转换类型错误

Java 列表作为第一项应始终具有特定值

java - 实现和集合

generics - Kotlin - "where"通用约束问题

ios - 在 UITextField 中关闭键盘

ios - Swift - 执行从右到左的seguewithidentifier过渡样式

ios - IBInspectable 属性停止显示

java - 泛型通配符不接受实现接口(interface)的类