//: Playground - noun: a place where people can play
import UIKit
/*
* 本节主要内容:
* 1.循环语句
*/
for index in 0..<10 {
print("index is \(index)")
}
// 需求:计算2的10次方
var result = 1
var baseValue = 2
// 下划线_是忽略循环次数(忽略区间运算符)
for _ in 10...19 {
result *= baseValue
}
print(result)
// 递减循环
for index in (1...10).reversed() {
print("decrement index is \(index)")
}
// 设置步长不是1
for index in stride(from: 0, to: 10, by: 2) {
print("stride增: \(index)")
}
for index in stride(from: 10, to: 0, by: -2) {
print("stride减: \(index)")
}
/*
* 需求: a和b两个人投色子, 点数大的赢一次, 任意一个人连续赢三次, 循环结束
* 要求: while循环
*/
// a和b分别赢的次数
var aWin = 0
var bWin = 0
// 记录投的次数
var gameCount = 0
// 结束条件: aWin == 3 || bWin == 3
// while条件: !(aWin == 3 || bWin == 3)
while aWin < 3 && bWin < 3 {
gameCount += 1
// 产生两个随机数[1, 6]
let aRandomValue = arc4random_uniform(6) + 1
let bRandomValue = arc4random_uniform(6) + 1
if aRandomValue > bRandomValue {
print("A Win once!")
aWin += 1
bWin = 0
} else if aRandomValue < bRandomValue {
print("B Win once!")
bWin += 1
aWin = 0
} else {
print("Draw!")
aWin = 0
bWin = 0
}
}
// 三目运算符判定谁赢
let winner = aWin == 3 ? "A" : "B"
print("After \(gameCount) games, \(winner) wins.")
Swift 系统学习 06 循环语句
最新推荐文章于 2017-08-22 20:01:14 发布