当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Swift stride(from:through:by:)用法及代码示例

函数

stride(from:through:by:)

返回从起始值到(可能包括)结束值的序列,步进指定的量。

声明

func stride<T>(
    from start: T,
    through end: T,
    by stride: T.Stride
) -> StrideThrough<T> where T : Strideable

返回值

start 到并可能包括 end 的序列。序列中的每个值都由 stride 分隔。

参数

start

用于序列的起始值。如果序列包含任何值,则第一个是 start

end

限制序列的结束值。 end 是结果序列的一个元素当且仅当它可以使用 stride 的步骤从 start 生成。

stride

每次迭代要逐步执行的量。一个正的stride向上迭代;负数 stride 向下迭代。

详述

您可以使用此函数跨越符合Strideable 协议的任何类型的值,例如整数或浮点类型。从 start 开始,序列的每个连续值都会添加 stride 直到下一个值超出 end


for radians in stride(from: 0.0, through: .pi * 2, by: .pi / 2) {
    let degrees = Int(radians * 180 / .pi)
    print("Degrees: \(degrees), radians: \(radians)")
}
// Degrees: 0, radians: 0.0
// Degrees: 90, radians: 1.5707963267949
// Degrees: 180, radians: 3.14159265358979
// Degrees: 270, radians: 4.71238898038469
// Degrees: 360, radians: 6.28318530717959

您可以使用stride(from:through:by:) 创建一个向上或向下跨步的序列。将负值作为stride 传递以创建从较高起点到较低终点的序列:


for countdown in stride(from: 3, through: 1, by: -1) {
    print("\(countdown)...")
}
// 3...
// 2...
// 1...

您作为end 传递的值不能保证包含在序列中。如果从 start 步进 stride 不会产生 end ,则序列中的最后一个值将是超出 end 之前的一步。


for multipleOfThree in stride(from: 3, through: 10, by: 3) {
    print(multipleOfThree)
}
// 3
// 6
// 9

如果您将值传递为远离 endstride ,则序列不包含任何值。


for x in stride(from: 0, through: 10, by: -1) {
    print(x)
}
// Nothing is printed.

可用版本

iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+

相关用法


注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 stride(from:through:by:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。