Swift-- 控制语句

2019-08-11  本文已影响0人  优雅的步伐

分支语句

if 语句

if语句中的条件表达式可以不加括号

/**
 分支--if语句
 **/

var examScore = 95

if examScore >= 85 {
    print("OK")
}

if examScore < 60 {
    print("不及格")
}

if examScore >= 60 && examScore < 85 {
    print("很好")
}

if score < 60 {
    print("不及格")
}else {
    print("及格")
}

let testScore = 76
var grade: Character

if testScore >= 90 {
    grade = "A"
}else if testScore >= 80 {
    grade = "B"
}else if testScore >= 70 {
    grade = "C"
}else if testScore >= 60 {
    grade = "D"
}else {
    grade = "F"
}

print(grade)

switch语句

/**
 switch语句
 **/

//使用整数比较
let testScore2 = 86
var grade2: Character

switch testScore2 / 10 {
case 9:
    grade = "优"
case 8:
    grade = "良"
case 7, 6:
    grade = "中"
default:
    grade = "差"
}

print(grade)

//使用小数比较
let value = 1.000
var desc: String

switch value {
case 0.0:
    desc = "最小值"
case 0.5:
    desc = "中值"
case 1.0:
    desc = "最大值"
default:
    desc = "其他值"
}

print(value)


//使用字符串比较
let level = "优"
desc = ""

switch level {
case "优":
    desc = "90分以上"
case "良":
    desc = "80分--90分"
case "中":
    desc = "70分--80分"
case "差":
    desc = "低于60分"
default:
    desc = "无法判断"
}
print(desc)

guard语句

guard语句是Swift2.x新添加的关键字,与if语句非常类似,可以判断一个条件为true情况下执行某语句,否则终止或执行某语句。它的设计目的是替换复杂if-else语句的嵌套,提高程序的可读性。

guard设计的目的: 实现早期判断,遇到不符合条件的情况下,程序就会终止或跳过某条语句,避免大量使用if-else嵌套语句

/**
 分支--guard语句
 **/

//定义一个Blog(博客)结构体
struct Blog {
    let name: String?
    let URL: String?
    let Author: String?
}

//if语句
func ifStyleBlog(blog: Blog) {
    if let blogName = blog.name {
        print("博客名: \(blogName)")
    }else {
        print("这篇博客没有名字!")
    }
}

//guard语句
func guardStyleBlog(blog: Blog) {
    guard let blogName = blog.name else {
        print("这篇博客没有名字!")
        return
    }
    print("这篇博客名:\(blogName)")
}

//if嵌套语句
func ifLogStyleBlog(blog: Blog){
    if let blogName = blog.name {
        print("这篇博客名:\(blogName)")
    
        if let blogAuthor = blog.Author {
           print("这篇博客由: \(blogAuthor)写的")
            if let blogURL = blog.URL {
                print("这篇博客网址: \(blogURL)")
            }else {
                print("这篇博客没有网址! ")
            }
        }else {
            print("这篇博客没有作者!")
        }
    }else {
        print("这b篇博客没有名字! ")
    }
}


//guard嵌套语句
func guardLogStyleBlog(blog: Blog) {
    guard let blogName = blog.name else {
        print("这篇博客没有名字! ")
        return
    }
    print("这篇博客名: \(blogName)")

    guard let blogAuthor = blog.Author else {
        print("这篇博客没有作者")
        return
    }
    print("这篇博客由\(blogAuthor)写的")

    guard let blogURL = blog.URL else {
        print("这篇博客没有网址!")
        return
    }
    print("这篇博客网址: \(blogURL)")
}

let blog1 = Blog(name: nil, URL: "51work6.com", Author: "Tom")
let blog2 = Blog(name: "Tony Blog", URL: "51work6.com", Author: "Tony")

let blog3 = Blog(name: nil, URL: nil, Author: "Tom")
let blog4 = Blog(name: "Tony Blog", URL: "51work6.com", Author: nil)

guardStyleBlog(blog: blog1)
guardStyleBlog(blog: blog2)

guardLogStyleBlog(blog: blog3)
guardLogStyleBlog(blog: blog4)

循环语句

/**
 循环语句
 **/

var i: Int64 = 0

//while语句
while i * i < 100_000 {
//    i++   //Swift3已经取消++、--操作
    i += 1  //或者写成 i = i+ 1
    print(i)
}

//repeat-while (代替do-while语句)
repeat {
    i += 1
    print(i)
} while i * i < 100_000


//for 语句
//Swift3 已经取消C风格for循环,下面的语句会报错
//for var i = 0; i < 10; i +=1 {
//    print(i)
//}

//正确写法
//区间循环
for i in 0 ..< 10 {
    debugPrint(i)
}

 //for-in循环
let number = [1, 2, 3, 4, 5, 6]
for item in number {
    print("is: \(item)")
}

//闭区间循环
//0...2表示0~2区间,包含数字2。
for i in 0...2 {
    print("hi")
}
//结果:
//hi
//hi
//hi

//如果你不需要区间序列内每一项的值,你可以使用下划线(_)替代变量名来忽略这个值:
for _ in 0..<2 {
    print("hello world!")
}
//结果:
//hello world!
//hello world!

//Swift 的 stride 函数返回一个任意可变步长 类型值的序列.

for i in stride(from: 5, to: 0, by: -1) {
    print(i)
// 打印结果为:5, 4, 3, 2, 1
//[5,0), 步长是-1
}

for i in stride(from: 5, through: 0, by: -1) {
    print(i)
    //打印结果为:5, 4, 3, 2, 1, 0
    //[5, 0]
}

跳转语句

break语句

break语句可用于while、repeat-while、for 和for-in 循环结构,它的作用是强行退出循环结构,不执行循环结构中剩余的语句。

break语句有两种方式:可以带标签,也可以不带标签。语法格式如下:
break //不带标签
break label //带标签,label是签名

break语句--不带标签

/**
 跳转语句
 **/

//break语句

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in 0 ..< numbers.count {
    if i  == 3 {
        break
    }
    print("Count is: \(i+1)")
}

//从0到5递增
for x in 0 ..< 5 {
    //从5到0递减
    for y in (0...5).reversed() {
        if y == x {
            break
        }
        print("(x, y) = (\(x), \(y))")
    }
}
break语句--带标签

//从0到5递增
label: for x in 0 ..< 5 {
    //从5到0递减
    for y in (0...5).reversed() {
        if y == x {
            break label
        }
        print("(x, y) = (\(x), \(y))")
    }
}

label即为符合条件后,跳出第一个for循环

打印结果如下


image.png
break语句 -- 带标签

//从0到5递增
 for x in 0 ..< 5 {
    //从5到0递减
    label2: for y in (0...5).reversed() {
        if y == x {
            break label2
        }
        print("(x, y) = (\(x), \(y))")
    }
}

label2即为符合条件后,跳出第二个for循环

打印结果如下


image.png

continue语句

continue语句用来结束本次循环,跳过循环中尚未执行的语句,接着进行终止条件的判断,以决定是否继续循环。

continue //不带标签
continue label //带标签,label是标签名

continue语句--不带标签

//continue语句
for i in 0 ..< numbers.count {
    if i  == 3 {
        continue
    }
    print("Count is: \(i+1)")
}

打印结果如下: 即i==3的时候不执行打印语句,返回到for语句继续执行

image.png
continue语句--带标签

//从0到5递增
label3: for x in 0 ..< 5 {
    //从5到0递减
    label4: for y in (0...5).reversed() {
        if y == x {
            continue label3
        }
        print("continue语句: (x, y) = (\(x), \(y))")
    }
}

当y==x时,跳过打印语句, 继续执行label3的for循环

打印结果如下:


image.png
continue语句--带标签

//从0到5递增
label5: for x in 0 ..< 5 {
    //从5到0递减
    label6: for y in (0...5).reversed() {
        if y == x {
            continue label6
        }
        print("continue语句: (x, y) = (\(x), \(y))")
    }
}

当y==x时, 跳过打印语句,继续执行label6的for循环
打印结果如下:

image.png

fallthrough语句

fallthrough是贯通语句, 只能使用在switch语句中。为了防止错误的发生,Swift中的 switch语句case分支默认不能贯通,即执行完一个case分支就跳出switch语句。但是凡事都有例外,如果你的算法真的需要多个case分支贯通,也可以使用fallthrough语句。

//fallthrough语句
var j = 1;
var k = 4
switch k {
case 1:
    j += 1
case 2:
    j += 1
case 3:
    j += 1
case 4:
    j += 1
    fallthrough
case 5:
    j += 1
    fallthrough
default:
    j += 1
}
print("j = \(j)")

首先执行case 4 中的语句,得出j = 2, 因为fallthrough可以贯通到下一条语句,执行case 5中得语句,再次得出结果j = 3, 又通过fallthrough贯通到default语句执行结果得 j = 4, 所以 打印结果为:j = 4

范围与区间运算符

闭区间含义如下:
下临界值 ≤ 范围 ≤ 上临界值 (...)
半开区间含义如下:
下临界值 ≤ 范围 < 上临界值 (..<)

switch中使用区间运算符

/**
 范围与区间运算
 **/

//示例1
let testScore3 = 80
var grade3: Character
switch testScore3 {
case 90 ... 100:
    grade3 = "优"
case 80 ..< 90:
    grade3 = "良"
case 60 ..< 80:
    grade3 = "中"
case 0 ..< 60:
    grade3 = "差"
default:
   grade3 = "无"
}
print("grade3 = \(grade3)")

打印结果为:良

//示例2
var student3 = (id: "1002", name: "李四", age:32, ChineseScore:80, EnglishScore:89)
var des3: String

switch student3 {
case (_,_,_, 90 ... 100, 90 ... 100):
    des3 = "优"
case (_,_,_, 80 ..< 90, 80 ..< 90):
    des3 = "良"
case (_,_,_, 60 ..< 80, 60 ..< 80):
    des3 = "中"
case (_,_,_, 60 ..< 80, 90 ... 100), (_,_,_, 90 ... 100, 60 ..< 80):
    des3 = "偏科"
case (_,_,_, 0 ..< 80, 90...100), (_,_,_, 90 ... 100, 60 ..< 80):
    des3 = "严重偏科"
default:
    des3 = "无"
}

print("说明:\(des3)")

打印结果为:
说明:良

for-in中使用区间运算符

//for-in中使用区间运算符
let numbers2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let count = numbers2.count
print("----半开区间----")
for i in 0 ..< count {
    print("第\(i+1)个元素:\(numbers2[i])")
}

print("----闭区间----")
for i in 0 ... 5 {
    print("第\(i+1)个元素:\(numbers2[i])")
}

打印结果如下:


image.png

值绑定

有时候在一些控制语句中可以将表达式的值临时赋给一个常量或变量,这些常量或变量能够在该控制语句中使用,这称为“值绑定”。
值绑定可以应用于if、guard和switch等控制语句中。

/**
 值绑定
 **/

//定义一个Blog(博客)结构体
struct Blog {
    let name: String?
    let URL: String?
    let Author: String?
}

if语句中的值绑定

//if语句中的值绑定
func ifStyleBlog(blog: Blog) {
    if let blogName = blog.name,
        let blogURL = blog.URL,
        let blogAuthor = blog.Author {
    
        print("这篇博客名: \(blogName)")
        print("这篇博客由: \(blogAuthor)写的")
        print("这篇博客网址: \(blogURL)")
    }  else {
        print("这篇博客信息不完整!")
    }
}

guard语句中的值绑定

//guard语句中的值绑定
func guardStyleBlog(blog: Blog) {
    guard let blogName = blog.name,
        let blogURL = blog.URL,
        let blogAuthor = blog.Author else {
        
        print("这篇博客信息不完整!")
        return
    }
    print("这篇博客名: \(blogName)")
    print("这篇博客由: \(blogAuthor)写的")
    print("这篇博客网址: \(blogURL)")
}

let blog1 = Blog(name: nil, URL: "51work6.com", Author: "Tom")
let blog2 = Blog(name: "Tony Blog", URL: "51work6.com", Author: "Tony")

print("--blog1--")
guardStyleBlog(blog: blog1)
print("--blog2--")
guardStyleBlog(blog: blog2)

输出结果如下:


image.png

switch语句中的值绑定

//switch语句中的值绑定
var student3 = (id: "1002", name: "李四", age:32, ChineseScore:80, EnglishScore:89)
var des3: String

switch student3 {
case (_, _, let AGE, 90 ... 100, 90 ... 100):
    if AGE > 30 {
        des3 = "老优"
    }else {
        des3 = "小优"
    }
case (_, _, _, 80 ..< 90, 80 ..< 90):
    des3 = "良"
case (_, _, _, 60 ..< 80, 60 ..< 80):
    des3 = "中"
case (_, _, _, 60 ..< 80, 90 ... 100), (_,_,_, 90 ... 100, 60 ..< 80):
    des3 = "偏科"
case (_, _, _, 0 ..< 80, 90...100), (_,_,_, 90 ... 100, 60 ..< 80):
    des3 = "严重偏科"
default:
    des3 = "无"
}

print("说明:\(des3)")

let AGE就是值绑定,它是把第三个的值取出来放到AGE的变量里或者常量里, 在第一个case的范围内可以使用AGE的变量或者常量

与if语句和guard语句不同的是,switch语句中的值绑定不是可选类型。
打印结果为:
说明:良

where语句

在一些控制语句中使用where语句,进行条件过滤,where类似SQL语句中的where语句。能够使用where语句的控制语句有switch、for-in 等。此外,where语句还可应用于泛型。

在switch中使用where语句

var student4 = (id: "1002", name: "李四", age:32, ChineseScore:90, EnglishScore:91)
var des4: String

switch student4 {
case (_, _, let age, 90 ... 100, 90 ... 100) where age > 20:
    des4 = "优"
case (_, _, _, 80 ..< 90, 80 ..< 90):
    des4 = "良"
case (_, _, _, 60 ..< 80, 60 ..< 80):
    des4 = "中"
case (_, _, _, 60 ..< 80, 90 ... 100), (_, _, _, 90 ... 100, 60 ..< 80):
    des4 = "偏科"
case (_, _, _, 0 ..< 80, 90...100), (_, _, _, 90 ... 100, 60 ..< 80):
    des4 = "严重偏科"
default:
    des4 = "无"
}

print("说明4:\(des4)")

输出结果为:
说明4:优

在for-in中使用where语句

//在for-in中使用where语句
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("----for-in----")
for item in numbers where item > 5 {
    print("Count is: \(item)")
}

输出结果如下:


image.png

注意:在swift3.0中,if-let和guard语句中的where都用“,”替代了。

if语句中的where用,替代了

//if语句
let animalsAge: Int? = 20
if let age = animalsAge, age > 8 {
    print(age)
}

输出结果为:20

guard语句的where用,替代了

//guard语句
func guardStyleBlog2(blog: Blog) {
    guard let blogName = blog.name, blogName == "Tony Blog" else {
        print("这篇博客没有名字!")
        return
    }
    print("这篇博客名:\(blogName)")
}

let blog3 = Blog(name: nil, URL: "51work6.com", Author: "Tom")
let blog4 = Blog(name: "Tony Blog", URL: "51work6.com", Author: "Tony")

guardStyleBlog2(blog: blog3)
guardStyleBlog2(blog: blog4)

输出结果为:
这篇博客没有名字!
这篇博客名:Tony Blog

上一篇 下一篇

猜你喜欢

热点阅读