SwiftUI-Day4 循环语句

文章目录

  • 吐槽
  • 结果
  • For 循环
  • While循环
  • do..while循环
  • 退出循环
  • 退出嵌套循环
  • 继续执行下一条 - Skipping Items
  • 无限循环 - Infinite Loops

吐槽

Xcode升级,什么appdelegate都没有了,现在全是swiftUI。。。
下面的代码是playground的代码,不是swiftUI View。
参考资料:https://www.hackingwithswift.com/100/swiftui/4
时间:09 October, 2020

结果

运行快捷键:shift+command+回车
删除当前行:option+D

For 循环

下划线表示不需要循环变量

let count = 1...10

for number in count {
    print("Number is \(number)")
}

let albums = ["Red", "1989", "Reputation"]

for album in albums {
    print("\(album) is on Apple Music")
}
print("Players gonna ")

for _ in 1...5 {
    print("play")
}

While循环

var number = 1

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

do…while循环

var number = 1

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

退出循环

while countDown >= 0 {
    print(countDown)

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

退出嵌套循环

给外层循环起个名字,然后break 外层循环

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
        }
    }
}

继续执行下一条 - Skipping Items

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

    print(i)
}

无限循环 - Infinite Loops

var counter = 0

while true {
    print(" ")
    counter += 1

    if counter == 273 {
        break
    }
}

你可能感兴趣的:(swift)