iOS

swift for 循环 看我就够了 (swift5)

2021-04-06  本文已影响0人  静守幸福

基本循环


// 正向数组
for  index  in 0...length {
}
for  index  in 0..<length {
}

// 反向数组
for  index  in 0...length.reversed() {
}

定长步长值 for循环

/// - Parameters:
///   - start: The starting value to use for the sequence. If the sequence
///     contains any values, the first one is `start`.
///   - end: An end value to limit the sequence. `end` is never an element of
///     the resulting sequence.
///   - stride: The amount to step by with each iteration. A positive `stride`
///     iterates upward; a negative `stride` iterates downward.
/// - Returns: A sequence from `start` toward, but not including, `end`. Each
///   value in the sequence steps by `stride`.
@inlinable public func stride<T>(from start: T, to end: T, by stride: T.Stride) -> StrideTo<T> where T : Strideable

     for radians in stride(from: 0.0, to: .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

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

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

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


to  不包含边界值  through  包含边界值

变长步长值 for循环

for var k in sequence(first:  1, next: {  2 * $0 + 1 < length ? 2 *$0 + 1 : nil
        })

for var k in sequence(first:  1, next: { element in
            return 2 * i + 1 < length ? 2 * i + 1 : nil
        })

first  变长开始的位置
next   步长公式   返回  nil 的时候 表示停止
不在这里停止的话 在for循环里面判断临界值 退出

上一篇 下一篇

猜你喜欢

热点阅读