简体   繁体   中英

Why does stride function work like this in Swift?

Below the first code snippet prints 1

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

but why the below snippet prints nothing?

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

For a positive stride amount, stride(from:through:by:) returns a sequence of all values x satisfying

start <= x and x <= end

which can be reached from the start value by adding the stride zero or more times. For a negative stride, the condition is the other way around:

start >= x and x >= end

That behavior is symmetric with respect to positive and negative strides:

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

The implementation can be found in Stride.swift in the Swift source code repository:

  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
  }

Your first example

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

prints 1 because that value satisfies 1 >= 1 and 1 >= 1 . Your second example

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

prints nothing because no value satisfies both conditions 1 >= x and x >= 2 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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