當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。