Swift小课

100 Days of Swift - 04 Day: Swif

2022-12-09  本文已影响0人  NieFeng1024

100 Days of Swift - 04 Day: loops, loops, and more loops

4.1 For loops(For 循环)

4.1.1 示例

    let count = 1...10
    for number in count {
        print("Number is \(number)")
    }

    for _ in 1...5 {
        print("play")
    }
    let albums = ["Red", "1989", "Reputation"]
    for album in albums {
        print("\(album) is on Apple Music")
    }

4.2 while 循环

    var number = 1
    while number <= 20 {
        print(number)
        number += 1
    }
    print("Ready or not, here I come!")

4.3 repeat 循环

    var number = 1
    repeat {
        print(number)
        number += 1
    } while number <= 20
    print("Ready or not, here I come!")
let numbers = [1, 2, 3, 4, 5]
var random = numbers.shuffled()

while random == numbers {
    random = numbers.shuffled()
}
let numbers = [1, 2, 3, 4, 5]
var random: [Int]

repeat {
    random = numbers.shuffled()
} while random == numbers

4.4 退出循环

var countDown = 10
while countDown >= 0 {
    print(countDown)

    if countDown == 4 {
        print("I'm bored. Let's go now!")
        break
    }

    countDown -= 1
}

let scores = [1, 8, 4, 3, 0, 5, 2]
var count = 0

for score in scores {
    if score == 0 {
        break
    }

    count += 1
}

4.5 退出多层循环

outerLoop: for i in 1...10 {
    for j in 1...10 {
        let product = i * j
        print ("\(i) * \(j) is \(product)")

        if product == 50 {
            print("It's a bullseye!")
            break outerLoop
        }
    }
}

4.6 跳过循环

for i in 1...10 {
    if i % 2 == 1 {
        continue
    }

    print(i)
}

4.7 小结

声明:本文创作来自hackingwithswift

上一篇 下一篇

猜你喜欢

热点阅读