一、 实验目的:
- 掌握Swift常用运算符的使用
- 掌握Swift控制流的使用
二、实验原理:
- 赋值运算符的作用
- 算术运算符支持的数据类型
- 关系运算符的定义
- 逻辑运算符的真值表
- 区间运算符的类型与特点
- if语句的语法
- switch语句的语法
- for…in语句的语法
- repeat…while语句的语法
三、实验步骤及内容:
1.赋值运算符
//赋值运算符
var str = “Hello, playground”
var newStr = str
let (a,b,c) = (1,2,3)
print(a)
print(b)
print(c)
2.算术运算符
//算术运算符
var a : Int = 8
var b : Int = 2
print(a+b)
print(a-b)
print(a*b)
print(a/b)
//字符串拼接运算符
var str1 : String = “Hello,”
var str2 : String = “world!”
print(str1+str2)
//取余运算符
var a : Int = 9
var b : Int = 2
a % b
//自增/减运算符
var a = 3
a += 1
let b = a
a -= 1
let c = a
3.关系运算符
//关系运算符
var a = 3, b = 6
a == b
a != b
a > b
a < b
a >= b
a <= b
if a == b {
print(”a is \(a), b is \(b), they are equal.”)
} else {
print(”a is \(a), b is \(b), they are not equal!”)
}
4.逻辑运算符
//非运算符
var on : Bool = false
if !on {
print(”the light is off”)
}
/与运算符
var on : Bool = false
var sunshine : Bool
var indoors : Bool
func lightControl(sunshine:Bool,indoors:Bool) {
on = (!sunshine) && indoors
if !on {
print(”turn light off”)
} else {
print(”turn light on”)
}
}
sunshine = false
indoors = true
lightControl(sunshine:sunshine, indoors:indoors)
//或运算符
var off : Bool = false
var sunshine : Bool
var indoors : Bool
func lightControl(sunshine:Bool,indoors:Bool) {
off = sunshine || (!indoors)
if off {
print(”turn light off”)
} else {
print(”turn light on”)
}
}
sunshine = false
indoors = true
lightControl(sunshine:sunshine, indoors:indoors)
5.三元运算符
//三元运算符
let contentHeight = 100
let bottomHeight = 20
var hasHeader = true
let pageHeight = contentHeight + bottomHeight + (hasHeader ? 30 : 10)
6.区间运算符
//区间运算符
for i in 0...3 {
print(i)
}
for i in 0..<3 {
print(i)
}
7.控制流
//区间循环1
for i in 1...6 {
print(”No.\(i);”)
}
//区间循环2
for _ in 1...6 {
print(”Execute!”)
}
//while循环
var i = 0
while i < 5 {
print(”i = \(i)”)
i += 1
}
//repeat-while循环
i = 0
repeat {
print(”i = \(i)”)
i += 1
} while i < 5
//if-else if-else
var season = “autumn”
if season == “spring” {
print(”All trees turn green.”)
} else if season == “summer” {
print(”It's too hot.”)
} else if season == “autumn” {
print(”Leaves are falling.”)
} else {
print(”Snow will come!”)
}
//switch
enum month {
case January
case February
case March
case April
case May
case June
case July
case August
case September
case October
case November
case December
}
var curMonth = month.February
switch curMonth {
case month.January : print(”the first month of a year”)
case month.February : print(”There is the most important festival in this month”)
case month.April,month.May,month.June : print(”month of the second season”)
default : print(”\(curMonth) doesn't match any case.”)
}
//switch匹配范围
var curMonth = 5
switch curMonth {
case 1...3 : print(”the first season”)
case 4...6 : print(”the second season”)
default : print(”the latter half of the year.”)
}
//switch匹配元组
var classInfo = (2015, “Computer Science”)
switch classInfo {
case (2016, “Computer Science”): print(classInfo)
case (2016, _): print(”2016's other class”)
case (_,”Computer Science”): print(”Computer Science Class in other year”)
default : print(”we don't care this class information”)
}
//值绑定
classInfo = (2012, “Medicine”)
switch classInfo {
case (let year, “Computer Science”): print(”Year \(year)'s Computer Science Class”)
case (2016, let course): print(”2016's class \(course)”)
case let (year,course): print(”Class \(course) in year \(year)”)
}
//where语句
switch classInfo {
case let (year,_) where year == 2015 :
print(”Class \(year) in year 2015”)
case let (_,course) where course == “Medicine” : print(”Class Medicine in year \(course)”)
case let (year,course) :
print(”Class \(course) in year\(year)”)
}
//控制转移语句1
for i in 1...6 {
if i == 4 {
continue
}
print(”No.\(i)”)
}
//控制转移语句2
for i in 1...6 {
if i == 4 {
break
}
print(”No.\(i)”)
}
//练习题
var sum = 0
for number in 1...100 {
sum += number
}
print(”Sum of 1+2+...+98+100 = \(sum)”)
var number = 0
sum = 0
while number <= 100 {
sum += number
number += 1
}
print(”Sum of 1+2+...+98+100 = \(sum)”)
number = 0
sum = 0
repeat {
sum += number
number += 1
} while number <= 100
print(”Sum of 1+2+...+98+100 = \(sum)”)
var score = 88
if score < 60 {
print(”Fail”)
} else if score < 70 {
print(”Pass”)
} else if score < 80 {
print(”Common”)
} else if score < 90 {
print(”Good”)
} else {
print(”Excellent”)
}
var grade = ““
switch score {
case 0...59 : grade = “Fail”
case 60...69 : grade = “Pass”
case 70...79 : grade = “Common”
case 80...89 : grade = “Good”
case 90...100 : grade = “Excellent”
default : print(”Unreasonable Score!”)
}
var subject = “Math”
var grade = “Excellent”
var subjectInfo = (grade, subject)
switch subjectInfo {
case (”Fail”, _): print(”Fail”)
case (”Pass”, _): print(”Pass”)
case (”Excellent”, “Math”): print(”Math is Excellent”)
case (”Excellent”, “Physics”): print(”Physics is Excellent”)
default : print(”Common or Good”)
}
subjectInfo = (”Pass”, “Math”)
switch subjectInfo {
case (”Fail”, let subject): print(”Subject \(subject) is Fail”)
case (”Pass”, let subject): print(”Subject \(subject) is Pass”)
case (”Excellent”, “Math”): print(”Math is Excellent”)
case (”Excellent”, “Physics”): print(”Physics is Excellent”)
default : print(”Common or Good”)
}
subjectInfo = (”Excellent”, “Physics”)
switch subjectInfo {
case (”Fail”, let subject): print(”Subject \(subject) is Fail”)
case (”Pass”, let subject): print(”Subject \(subject) is Pass”)
case let (grade, subject) where (subject == “Math” || subject == “Physics”) && grade == “Excellent”: print(”\(subject) is \(grade)”)
default : print(”Common or Good”)
}
var product = 1
var count = 1
while count < 100 {
count += 1
if product > 100 {
print(”count is \(count), product is \(product).”)
break
}
product *= count
}
print(”Cycle is stopped!”)
print(”count is \(count), product is \(product).”)
product = 1
count = 1
while count < 100 {
count += 1
if product > 100 {
print(”count is \(count), product is \(product).”)
continue
}
product *= count
}
print(”Cycle is stopped!”)
print(”count is \(count), product is \(product).”)
四、实验结果与分析:
本次实验,主要学习了Swift常用运算符和控制流的使用。通过本次的学习,我了解到Swift支持大多数标准C运算符,并有所改进。Swift赋值运算符(=)不返回值,以防止在相等运算(==)意图时错误地使用它。算术运算符(+,-,,/,%等)检测和禁止值溢出,避免数据比类型允许范围更大或更小。在面对数值溢出行为可以选择使用溢出运算符,在溢出运算符中描述。提供了在C中不存在的区间运算符,如a…<b和a…b表示一系列值范围的快捷方式。在实验中,我主要会因为自己的粗心大意,方法使用不恰当导致运行结果出现误差,检查出错误后,基本所有的实验结果都可以正常运行出来,特别需要注意的是,Swift默认禁止值溢出,但可使用溢出符号选择溢出行为: a &+ b,另外+可用于String进行连接即可。
五、实验总结:
通过本次课程的学习,以及自己实际操作后,我对Swift常用运算符和控制流的使用了解如下:
1.swift赋值运算符的作用是:将常量、变量或表达式的值赋给某一个变量。
2.swift算术运算符支持的数据类型:Swift 中所有数值类型都支持了基本的四则算术运算符:加法(+)、减法(-)、乘法()、除法(/)。与 C 语言和 Objective-C 不同的是,Swift 默认情况下不允许在数值运算中出现溢出情况。但是你可以使用 Swift 的溢出运算符来实现溢出运算(如a &+ b)。
3.swift关系运算符的定义: swift关系运算符是⽐较两个表达式⼤⼩关系的运算,它的结果是true或false,即布尔型数据。如果表达式成⽴结果为true, 否则为false。果表达式成⽴结果为true, 否则为false。
4.swift逻辑运算符的真值表: 逻辑运算是用来判断一件事情是“成立”还是“不成立”,或者是“真”还是“假”的,判断的结果只有两个值,用数字表示就是“1”和“0”。其中“1”表示该逻辑运算的结果是“成立”的,“0”表示这个逻辑运算的结果是“不成立”的。
5.swift区间运算符的类型与特点: 区间运算符(Range Operators)主要有2种:
闭区间运算符(n…m),n 不能大于 m,相当于数学的 [n, m]
半开区间运算符(n…<m),相当于数学的 [n, m)
6.if语句的语法: if语句有三种格式,分别是:
(1)【if(布尔表达式){执行语句}】;
(2)【if(布尔表达式){执行代码}else{执行代码}】;
(3)【if(布尔表达式){执行代码}else if(布尔表达式){执行代码}else{执行代码}】。
7.switch语句的语法:switch 语句允许测试一个变量等于多个值时的情况。 Swift 语言中只要匹配到 case 语句,则整个 switch 语句执行完成。一般在 switch 语句中不使用 fallthrough 语句,这里我们需要注意 case 语句中如果没有使用 fallthrough 语句,则在执行当前的 case 语句后,switch 会终止,控制流将跳转到 switch 语句后的下一行。如果使用了fallthrough 语句,则会继续执行之后的 case 或default 语句,不论条件是否满足都会执行。
注意:在大多数语言中,switch 语句块中,case 要紧跟 break,否则 case 之后的语句会顺序运行,而在 Swift 语言中,默认是不会执行下去的,switch 也会终止。如果你想在 Swift 中让 case 之后的语句会按顺序继续运行,则需要使用 fallthrough 语句。
8.for…in语句的语法:for -in循环用于将一组任务运行一定次数。这些循环遍历任何序列,如数组中的项、范围或字符串中的字符。for-in用来遍历一个区间(range)、序列(sequence)、集合(collection)、系列(progression)
9.repeat…while语句的语法:Repeat While循环与while循环相同, 但不同之处在于repeat … while循环的主体在检查测试表达式之前执行一次。在此循环中, 执行一次while循环的主体, 并在测试testExpression之后执行一次。
repeat {
// statements
…
} while (testExpression)
不管何种情况 repeat 肯定会执行一次,然后判断循环条件,这与 while 循环刚好相反,这在使用时需要注意。以上是我本次实验中所学习了解到的内容,如理解有误,恳请老师批评指正,谢谢老师!