Swift笔记:For-In、While 循环、if条件语句

For-In 循环

for-in循环是用来遍历一个集合里面的所有元素,例如由数字表示的区间、数组中的元素、字符串中的字符。

for index in 1...5
{
    print("\(index)*5 = \(index*5)")
}
//1*5 = 5
//2*5 = 10
//3*5 = 15
//4*5 = 20
//5*5 = 25

for in遍历数组

var arrayStr:[String] = ["h","b","c","d","g","f"]
for indexStr in arrayStr
{
    print("遍历数组\(indexStr)")
}
//遍历数组h
//遍历数组b
//遍历数组c
//遍历数组d
//遍历数组g
//遍历数组f

遍历字典

var dict = ["1" :"d","2":"b","3":"g"]
for (key1,value1) in dict
{
    print("key = \(key1) value = \(value1)")
}
//key = 2 value = b
//key = 1 value = d
//key = 3 value = g

While
while循环从计算单一条件开始。如果条件为true,会重复运行一系列语句,直到条件变为false。

下面是一般情况下 while 循环格式:

while condition {  
    statements
}

Repeat-While

while循环的另外一种形式是repeat-while,它和while的区别是在判断循环条件之前,先执行一次循环的代码块,然后重复循环直到条件为false。

Swift语言的repeat-while循环合其他语言中的do-while循环是类似的。

一般情况下 repeat-while循环的格式:

repeat {
    statements
} while condition

If

if语句最简单的形式就是只包含一个条件,当且仅当该条件为true时,才执行相关代码:

var temperatureInFahrenheit = 30
if temperatureInFahrenheit <= 32 {
    print("It's very cold. Consider wearing a scarf.")
}
// 输出 "It's very cold. Consider wearing a scarf."

if语句允许二选一,当条件为false时,执行 else 语句:

temperatureInFahrenheit = 40
if temperatureInFahrenheit <= 32 {
    print("It's very cold. Consider wearing a scarf.")
} else {
    print("It's not that cold. Wear a t-shirt.")
}
// 输出 "It's not that cold. Wear a t-shirt."
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值