A partial interval extending upward from a lower bound.
SDK
- Xcode 9.0+
Framework
- Swift Standard Library
Declaration
Overview
You create Partial
instances by using the postfix range operator (postfix ...
).
You can use a partial range to quickly check if a value is contained in a particular range of values. For example:
You can use a partial range of a collection’s indices to represent the range from the partial range’s lower bound up to the end of the collection.
Using a Partial Range as a Sequence
When a partial range uses integers as its lower and upper bounds, or any other type that conforms to the Strideable
protocol with an integer stride, you can use that range in a for
-in
loop or with any sequence method that doesn’t require that the sequence is finite. The elements of a partial range are the consecutive values from its lower bound continuing upward indefinitely.
Because a Partial
sequence counts upward indefinitely, do not use one with methods that read the entire sequence before returning, such as map(_:)
, filter(_:)
, or suffix(_:)
. It is safe to use operations that put an upper limit on the number of elements they access, such as prefix(_:)
or drop
, and operations that you can guarantee will terminate, such as passing a closure you know will eventually return true
to first(where:)
.
In the following example, the ascii
sequence is made by zipping together the characters in the alphabet
string with a partial range starting at 65, the ASCII value of the capital letter A. Iterating over two zipped sequences continues only as long as the shorter of the two sequences, so the iteration stops at the end of alphabet
.
The behavior of incrementing indefinitely is determined by the type of Bound
. For example, iterating over an instance of Partial
traps when the sequence’s next value would be above Int
.