swift入门教程系列7-控制流

控制流
总的来说使用方式和C,C++,Objective C等差不多
这里讲解可能会少一点,大家实际写点代码就会用了,很简单,可以侧重看看switch,swift中的swift功能更多一些
有一点特别要注意的是,swift中的条件表达式的结果一定是Bool类型的
也就是说
var a  = 19
if a{
}
这样的表达式是不对的,因为a是Int类型

1、if

常用的if也就三种

if bool{
}

if bool{
}
else{
}

if bool{
}
else if{
}
else{
}

2、for
swift中 for循环分为for 和for in两种
对于for in
这里的index隐式被声明为常量,不需要提前声明
for index in 1...10{
    println(index)
}
如果无需index的具体值,可以用下划线代替
for _ in 1...10{
    println("hello hwc")
}
for in 最常用的还是用来遍历数组,字典
var dictionary = [1:"one",2:"two",3:"three"]
for (key,value) in dictionary{
println("\(key)->\(value)")
}
当然,也可以用for的条件递增
for var index = 0;index < 10;++index{
    println(index)
}
3、while
while condition{
    statements
}
var i = 0
while  i < 10{
   println(i)
   i++
}

do{
}while condition
var i = 0
do{
    println(i)
    i++
}while i < 10

4 switch

switch temp{
case value1:
	println(value1)
case value2:
	println(value2)
defalut:
	println(default)
}

swift中的switch语句可以不用break,会自动跳出
swift中,每个case语句至少要执行一个局域
所以
case value1:
case value2:
println("")
是会报错的

在swfit中,如果想要匹配多个值,
switch oenValue{
    case value1:
println("1")
    case value2...value4:
println("234")
    default:
        println("default")
}

在swift中, switch可以直接匹配元组,这个十分方便
元组中可以是区间,也可以用_匹配任何值
case (0,0):匹配(0,0)
case (0..3,1)匹配(0,1)(1,1)(2,1)
case (_,1)匹配任何(Int,1)
举个例子
let somePoint = (1, 1)
switch somePoint {
case (0, 0):
println("(0, 0) is at the origin")
case (_, 0):
println("(\(somePoint.0), 0) is on the x-axis")
case (0, _):
println("(0, \(somePoint.1)) is on the y-axis")
case (-2...2, -2...2):
println("(\(somePoint.0), \(somePoint.1)) is inside the box")
default:
println("(\(somePoint.0), \(somePoint.1)) is outside of the box")
}


case的分支语句可以通过where增加额外判断
let somePoint = (1, 1)
switch somePoint {
	case let(x,y) where x == y:
		println("x is equal to y")
	default:
		println("x is not equal to y" )
}

5 continue break fallthrough return 
continue,终止循环体中的这次操作,继续下一次操作
for index in 1...10{
   if index % 2 == 1{
	continue
   }
   println(index)
}
break,立即结束当前控制流的执行
let x = 10
switch x
{
    case 10:
	println("right")
    default:
        break
}
fallthrough贯穿,从swift中的一个case贯穿到下一个case
swift中,默认在一个case结束后,不管有没有break,都会跳出switch语句,如果想要像其他语言一样,则使用fallthrough关键字
let x = 0
switch x
{
    case 0:
println(0)
fallthrough
    case 1:
println(1)
    case 2:
println(2)
    default:
    println("defalult")
}
执行会发现输出0 1

带标签的语句
当我们有多层循环,或者多层switch的时候,如何知道一个continue或者break是终止那一层控制流呢?Swift提供了一种方便的方式:带标签的语句
var x = 1
var y = 1
firstLoop:while x < 5{
	secondLoop:while y < 6{
  		//continue firstLoop or continue secondLoop
	}
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值