且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

数组范围迅速

更新时间:2023-01-23 18:25:13

您可以通过以下方式实现所需的目标:

You can achieve what you're looking for in the following way:

1..创建一个自定义结构来存储开始和结束索引.如果 startIndex endIndex nil ,这将表示该范围沿该方向无限扩展.

1. Create a custom struct to store a start and end index. If startIndex or endIndex is nil this will be taken to mean the range extends infinitely in that direction.

struct UnboundedRange<Index> {
    var startIndex, endIndex: Index?

    // Providing these initialisers prevents both `startIndex` and `endIndex` being `nil`.
    init(start: Index) {
        self.startIndex = start
    }

    init(end: Index) {
        self.endIndex = end
    }
}

2..在我的选择中,定义运算符以创建 BoundedRange ,因为必须使用初始化程序会导致一些相当难看的代码.

2. Define operators to create an BoundedRange as having to use the initialisers will lead to some quite unsightly code, in my option.

postfix operator ... {}
prefix  operator ... {}

postfix func ... <Index> (startIndex: Index) -> UnboundedRange<Index> {
    return UnboundedRange(start: startIndex)
}

prefix func ... <Index> (endIndex: Index) -> UnboundedRange<Index> {
    return UnboundedRange(end: endIndex)
}

一些用法示例:

1...  // An UnboundedRange<Int> that extends from 1 to infinity.
...10 // An UnboundedRange<Int> that extends from minus infinity to 10.

3..扩展 CollectionType ,以便它可以处理 UnboundedRange s.

3. Extend the CollectionType so it can handle UnboundedRanges.

extension CollectionType {
    subscript(subrange: UnboundedRange<Index>) -> SubSequence {
        let start = subrange.startIndex ?? self.startIndex
        let end = subrange.endIndex?.advancedBy(1) ?? self.endIndex
        return self[start..<end]
    }
}

4..要在给定的示例中使用它,请执行以下操作:

4. To use this in your given example:

let array = ["a", "b", "c"]

array[1...] // Returns ["b", "c"]
array[...1] // Returns ["a", "b"]