forked from apple/swift
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Stride] Check boundaries before calculating next step
The current implementation of `Stride(To|Through)Iterator` verifies the completion of the sequence by pre-calculating the current value and checking if it exceeds the end boundary before returning it. It, then, requires for a value beyond the boundary to be returned by `Strideable.advanced(by:)`. Instead of stepping one value after the boundaries, this implementation verifies if the distance between the current element and the end element is smaller than the stride step. This allows stopping the iterator before that element is required. After this change two usages of `Strideable` conformance become available: * The use of frontier values on `stride(from:(to|through):by:)` As described in [SR-2016](https://bugs.swift.org/browse/SR-2016), this would now function properly as it'd be no longer requried for the "impossible" value `UInt8(256)` to briefly exist in order to complete the iteration: ``` stride(from:0 as UInt8, through: 255, by: 2) ``` * The use of `Strideable` on enums with a finite number of cases While it is currently possible to support it on enums, it requires a special `case` to handle the past-frontier case. This enables the following use-case: ``` enum Test: Int, Strideable { case one = 1, two, three, four typealias Stride = Int func distance(to other: Self) -> Int { return other.rawValue - self.rawValue } func advanced(by: Int) -> Self { return Self(rawValue: self.rawValue + by)! } } stride(from: Test.one, through: Test.four, by: 2) ```
- Loading branch information
1 parent
da37637
commit b846dba
Showing
2 changed files
with
51 additions
and
20 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters