Swift 学习-控制流(五)

For in 遍历集合中元素

for index in1...5 {

print("\(index)times 5 is \(index * 5)")

}

如果你不需要知道区间内每一项的值,你可以使用下划线(_)替代变量名来忽略对值的访问:

let base = 3

let power = 10

var answer = 1

for _ in1...power {

    answer *= base

}

print("\(base)to the power of \(power) is \(answer)")

// 输出 "3 tothe power of 10 is 59049"

For 循环

 格式定义如下:

for initialization; condition; increment { statements }

//index只在循序体内有效,如果要在外部访问则需要在外部声明。

for var index = 0; index < 3;++index

 {

print("index is\(index)")

}

// index is 0

// index is 1

// index is 2

while循环

格式定义如下:

while condition{ statement }

var st = 3

while st < 1

{

Print(“st:\(st)”)

st --
}

Repeat-While(类似do-while) 循环

格式定义如下:

repeat { statements }while condition

let finalSquare = 25

var board = [Int](count:finalSquare + 1, repeatedValue: 0)

 board[03] = +08; board[06] = +11; board[09] =+09; board[10] = +02

 board[14] = -10; board[19] = -11; board[22] =-02; board[24] = -08

 var square = 0

var diceRoll = 0

repeat {

// 顺着梯子爬上去或者顺着蛇滑下去

square += board[square]

// 掷骰子 if ++diceRoll== 7 { diceRoll = 1 }

// 根据点数移动

square += diceRoll

} while square < finalSquare

 print("Game over!")

if语句

var temperatureInFahrenheit = 30

if temperatureInFahrenheit <=32

{

 print("It's very cold. Consider wearing ascarf.")

}

//---------------

If .. {

}else if .. {

}else {

}

Switch 语句

格式定义如下:

switch some value to consider {

case value 1:

   respond to value 1

case value 2,

value 3:

   respond to value 2 or 3

default:

   otherwise, do something else

}

switch特点:

a)   不存在隐式的贯穿(No Implicit Fallthrough

 Swift 中

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值