繁体   English   中英

为什么 stride function 在 Swift 中会这样工作?

[英]Why does stride function work like this in 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)
}

对于正的步幅量, 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM