使用模

时间:2016-04-24 09:04:27

标签: swift

由于C-style for语句已弃用,将在未来的Swift版本中删除,因此实现以下目标的最佳方法是:

for var i = startIndex; i != endIndex; i = (i + 1) % arrCount {
}

(我想迭代数组,但是从中间的某个地方开始并继续直到我到达我开始的索引)

编辑: startIndex> endIndex的

3 个答案:

答案 0 :(得分:2)

“while”应该是最好的:

var i = startIndex
while i != endIndex {
    i = (i + 1) % arrCount
}

答案 1 :(得分:1)

您可以非常轻松地移动原始数组,请参阅以下示例:

let array = [3,4,5,6,7]
let startIndex = 3
let endIndex = 2

let head = array[0..<endIndex] // [3, 4]
let tail = array[startIndex..<array.count] // [6, 7]
let shiftedArray = tail + head // [6, 7, 3, 4]

for element in shiftedArray {
    // do something
}

答案 2 :(得分:1)

这是使用自定义SequenceType&amp;的解决方案。关联的GeneratorType,如上面评论中的Sulthan所示。

从好的方面来说,这个序列非常可读且灵活。例如:

let startIndex = 3
let endIndex = 2
let array = [3, 4, 5, 6, 7]

ModuloSequence(start: startIndex, end: endIndex, divisor: array.count).map {
    array[$0]
}

从消极方面来说,实施起来相当冗长(无论如何,我的看法是:)

struct ModuloSequenceGenerator : GeneratorType {
    let end:Int, divisor:Int
    private var dividend:Int?

    init(start:Int, end:Int, divisor:Int) {
        self.dividend = start
        self.end = end
        self.divisor = divisor
    }

    mutating func next() -> Int? {
        guard let c = dividend where c != end else {
            return nil
        }
        dividend = (c + 1) % divisor
        return dividend
    }
}

struct ModuloSequence : SequenceType {
    let start:Int, end:Int, divisor:Int

    func generate() -> ModuloSequenceGenerator {
        return ModuloSequenceGenerator(start: start, end: end, divisor: divisor)
    }
}