首页 > 解决方案 > 为什么 stride 函数在 Swift 中会这样工作?

问题描述

在第一个代码片段下方打印 1

for i in stride(from: 1, through: 1, by: -1) {
    print(i)
}

但是为什么下面的代码段什么也没打印?

for i in stride(from: 1, through: 2, by: -1) {
    print(i)
}

标签: iosswift

解决方案


对于正的步幅量,返回所有满足stride(from:through:by:)的值的序列x

start <= x and x <= end

可以通过将步幅添加零次或多次来从起始值到达。对于负步幅,条件是相反的:

start >= x and x >= end

这种行为关于正向和负向步幅是对称的:

for i in stride(from: 0, through: 0, by: 1) { print(i) } // prints 0
for i in stride(from: 0, through: -1, by: 1) { print(i) } // prints nothing

for i in stride(from: 0, through: 0, by: -1) { print(i) } // prints 0
for i in stride(from: 0, through: 1, by: -1) { print(i) } // prints nothing

可以在 Swift 源代码存储库的Stride.swift中找到该实现:

  public mutating func next() -> Element? {
    let result = _current.value
    if _stride > 0 ? result >= _end : result <= _end {
      // Note the `>=` and `<=` operators above. When `result == _end`, the
      // following check is needed to prevent advancing `_current` past the
      // representable bounds of the `Strideable` type unnecessarily.
      //
      // If the `Strideable` type is a fixed-width integer, overflowed results
      // are represented using a sentinel value for `_current.index`, `Int.min`.
      if result == _end && !_didReturnEnd && _current.index != .min {
        _didReturnEnd = true
        return result
      }
      return nil
    }
    _current = Element._step(after: _current, from: _start, by: _stride)
    return result
  }

你的第一个例子

for i in stride(from: 1, through: 1, by: -1) { print(i) } 

打印1,因为该值满足1 >= 11 >= 1。你的第二个例子

for i in stride(from: 1, through: 2, by: -1) { print(i) }

什么都不打印,因为没有值同时满足条件1 >= xx >= 2.


推荐阅读