swift3.0流程控制

流程控制

1.for-in循环

for indexin 1...5 {

    //index是一个常量,其值在循环的每次迭代开始时自动设置。因此,索引不必在使用之前声明。

    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 10次幂是 59049

 

//遍历数组、字典

let names = ["Anna","Alex", "Brian","Jack"]

for namein names {

    print("Hello, \(name)!")

}

 

let numberOfLegs = ["spider":8, "ant": 6, "cat": 4]

for (animalName,legCount)in numberOfLegs {

    print("\(animalName)s have\(legCount) legs")

}

 

 

2.while循环

while循环执行一组语句,直到条件变为false

while条件 {

    语句

}

 

3.Repeat-While

在考虑循环的条件之前首先执行单次通过循环块。然后继续重复循环,直到条件为假

repeat {

    语句

} while 条件

 

4.条件语句if

var age =15

ifage <= 18 {

    print("未成年")

}

 

ifage <= 6 {

    print("该上幼儿园")

} else {

    print("该上小学了")

}

 

5.条件语句switch

switch判断条件 {

    case value 1:

        value 1的处理

    case value 2,

        value 3 :

        value2,3的处理

    default:

        默认值

}

 

let someCharacter:Character = "z"

switchsomeCharacter {

case"a":

    print("The first letterof the alphabet")

case"z":

    print("The last letterof the alphabet")

default:

    print("Some othercharacter")

}

//Thelast letter of the alphabet  

//注:整个switch语句在第一个匹配开关情况完成后立即完成其执行,而不需要显式break语句。

//虽然在Swift中不需要break,但是可以使用break语句来匹配和忽略特定的案例,或者在案例完成执行之前中断匹配的案例。

 

let anotherCharacter:Character = "a"

switchanotherCharacter {

case"a"://报错:无效,该案例没有实体值

case"A":

    print("The letterA")

default:

    print("Not the letterA")

}

 

//改为:

let anotherCharacter:Character = "a"

switchanotherCharacter {

case"a", "A":

    print("The letterA")//Theletter A

default:

    print("Not the letterA")

}

 

2>.间隔匹配

let approximateCount =62

let countedThings ="moons orbiting Saturn"

var naturalCount:String

switchapproximateCount {

case0:

    naturalCount = "no"

case1..<5:

    naturalCount = "a few"

case5..<12:

    naturalCount = "several"

case12..<100:

    naturalCount = "dozens of"

case100..<1000:

    naturalCount = "hundredsof"

default:

    naturalCount = "many"

}

print("There are\(naturalCount)\(countedThings).")//There are dozens of moons orbiting Saturn.

 

3>.元组匹配

使用元组在同一个switch语句中测试多个值。 可以针对不同的值或值的区间来测试元组的每个元素。或者,使用下划线字符(_)(也称为通配符模式)匹配任何可能的值。

let somePoint = (1,1)

switchsomePoint {

case (0,0):

    print("(0, 0) is at theorigin")

case (_,0):

    print("(\(somePoint.0), 0) is on thex-axis")

case (0,_):

    print("(0, \(somePoint.1)) is on they-axis")

case (-2...2,-2...2):

    print("(\(somePoint.0),\(somePoint.1)) is inside thebox")

default:

    print("(\(somePoint.0),\(somePoint.1)) is outside of thebox")//(1,1) is inside the box

}

 

4>.值绑定

将一个或多个匹配的值绑定到临时常量或变量,以在案例的主体中使用。称为值绑定。

let anotherPoint = (2,0)

switchanotherPoint {

case (let x,0):

    print("on the x-axiswith an x value of \(x)")//on the x-axis with an x value of 2

case (0, let y):

    print("on the y-axiswith a y value of \(y)")

case let (x, y):

    print("somewhere else at(\(x),\(y))")

}

 

5>.where

switch可以使用where子句来检查其他条件

 

let yetAnotherPoint = (1,-1)

switchyetAnotherPoint {

case let (x, y)where x == y:

    print("(\(x),\(y)) is on the line x ==y")

case let (x, y)where x == -y:

    print("(\(x),\(y)) is on the line x ==-y")//(1,-1) is on the line x == -y

case let (x, y):

    print("(\(x),\(y)) is just somearbitrary point")

}

 

 

6>.复合案例

共享同一主体的多个switch case可以通过在每个case之后写入几个模式来组合,在每个模式之间使用逗号。如果任何模式匹配,则认为情况匹配。如果列表很长,则可以在多行上写入模式。

let compoundChar:Character = "e"

switchcompoundChar {

case"a","e","i","o","u"://与英语中的所有五个小写元音相匹配

    print("\(compoundChar) is avowel")//eis a vowel

case"b", "c","d", "f", "g", "h", "j","k", "l", "m",

     "n","p","q","r","s","t","v","w","x","y","z"://匹配所有小写英语辅音。

    print("\(compoundChar) is aconsonant")

default://默认情况下匹配任何其他字符。

    print("\(compoundChar) is not avowel or a consonant")

}

 

7>.控制转移语句

控制转移语句通过将控制从一段代码转移到另一段代码来改变代码执行的顺序。 Swift有五个控制转移语句:

    continue

    break

    fallthrough

    return

    throw

 

continue结束当次循环,重新开始下一次迭代循环。

break语句立即结束对整个控制流语句的执行。

fallthroughSwift中的switch语句不会通过每个case的底部,并进入下一个。相反,整个switch语句在第一个匹配大小写完成后立即完成执行。可以根据具体情况选择fallthrough采用关键字逐渐减少的行为。

 

6.提前退出

//guard语句(如if语句)根据表达式的布尔值执行语句。使用guard语句要求条件必须为真,以便在执行保护语句后的代码。与if语句不同,guard语句总是有一个else子句 - 如果条件不为真,则执行else子句中的代码。

func greet(person: [String:String]) {

    guard let name = person["name"] else {

        return

   }

    print("Hello \(name)!")

   

    guard let location = person["location"]else {

        print("I hope theweather is nice near you.")

        return

   }

    print("I hope theweather is nice in \(location).")

}

greet(person:["name":"John"])//打印 Hello John!  I hope the weatheris nice near you.

greet(person:["name":"Jane","location":"Cupertino"])//打印 Hello Jane! I hope the weather is nicein Cupertino.

 

7.检查API可用性

Swift内置支持检查API可用性,确保您不会意外使用在给定部署目标上不可用的API

if #available(platformname version, ..., *) {

    如果API可用,则执行语句

} else {

    如果API不可用,则执行fallback语句

}

 

if #available(iOS10, macOS 10.12, *) {

    //iOS上使用iOS 10API,并在macOS上使用macOS 10.12 API

} else {

    //回到早期的iOSmacOSAPI

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值