一、实验目的:
- 掌握Swift编程方法。
- 掌握Swift数据类型。
二、实验原理:
- playground的界面与使用方法。
- 常量与变量的定义方法。
3.常量与变量的类型声明方法。
三、实验步骤及内容:
1. 常量与变量
// 常量的定义
let lengthOfTelephoneNumber = 8
let lengthOfIdentityCardNumber = 18
let lengthOfZipNumber = 6
//变量的定义
var totalVisits = 2000000
var numberOfMembers = 10000
var currentSpeed = 120
//常量,变量命名
var a_b = “a and b”
var aPerson = “one person”
let hello = “say hello”
let mul = “multiply operator”
var numOfApple = 88
//可读性强的命名
var numberOfStudents = 68
var idCardNumber = “320602201612120652”
let pi = 3.141516
//可读性弱的命名
var a = 68
var b = “320602201612120652”
let c = 3.141516
//类型声明
let name : String = ““
var age : Int = 0
//定义变量
var a_b = “a and b”
var aPerson = “one person”
var hello = “say hello”
//分配变量值
hello = “say hi”
a_b = “c and d”
//输出
print(a_b)
print(hello)
print(“The value of variable a_b is \(a_b)”)
print(aPerson)
//分隔符
var a_b = “a and b”, aPerson = “one person”, hello = “say hello”
let thisYear = “2022”
let myOrganisation = “QingChuan”
let myhobby = “Reading”
//练习题1
/*
the reference code for exercise
chapter: constant and variable
Author: Morre Paul
Organisation: QingChuan
Date: 2021-8-9
*/
//definition part
var radius : Double = 3.0
let pi : Double = 3.1415
var areaOfCircle : Double = pi * radius * radius
//output part
print(“radius = \(radius), pi = \(pi), so the area of circle is : \(areaOfCircle)”)
2. 整型和浮点型
let minValue = Int8.min
let maxOfInt8 = Int8.max
let maxOfInt16 = Int16.max
let maxOfInt32 = Int32.max
let maxOfInt64 = Int64.max
let num1:Int8 = -128
let num2:UInt16 = 65535
let num3: Int32 = -100_0000
//整型混合运算
let result = Int(num1) + Int(num2) + Int(num3)
//32位
let fNum1: Float = 3.1415
//64位
let dNum2: Double = 3.1415926
//浮点型混合元算
let sum = Double(fNum1) + dNum2
//越界赋值
let outBoundNum1 : UInt8 = -16
let outBoundNum2 : Int8 = 160
//越界运算
let outBoundNum1 : UInt8 = 16
let outBoundNum2 : Int8 = 120
let sum = Int8(outBoundNum1) + outBoundNum2
//练习题2
let maxOfInt32 = UInt32.max
let minOfUInt = UInt.min
let intNum: Int = 10000
let doubleNum: Double = -33.66
let sumInt = intNum + Int(doubleNum)
let sumDouble = Double(intNum) + doubleNum
let correctValue1 = 200
let correctValue2 : UInt8 = 200
//let correctValue3 : Int8 = 200
let value1 : Int16 = 20000
let value2 : Int8 = 10
//let multiResult = value1 * Int16(value2)
let multiResult = Int(value1) * Int(value2)
3. 浮点型
var daylight : Bool = true
var lightSwitch = false
if daylight {
lightSwitch = false
print(“It is daytime, so turn light switch off!”)
} else {
lightSwitch = true
print(“It is night, please turn light switch on!”)
}
//练习题3
var isWeekend : Bool = false
if isWeekend {
print(“Today may be Saturday or Sunday.”)
} else {
print(“Today is not Saturday or Sunday.”)
}
var sunnyDay = true
if sunnyDay {
print(“It's sunny.”)
} else {
print(“It's rainy or cloudy.”)
}
4.元组
//定义元组
let http404Error = (404, “Not Found”)
//元组赋值
let (Code, Description) = http404Error
print(Code)
print(Description)
//访问元组
print(http404Error.0)
print(http404Error.1)
let http406Error = (Code: 406, Description: “Not Acceptable”)
print(http406Error.Code)
print(http406Error.Description)
let rectangle = (len:10 , width:5)
print(rectangle.0)
print(rectangle.width)
print(rectangle)
//练习题4
//定义元组
let studentInfo = (60115, “Liang Zhang”, true)
//访问元组方法1
let (idNum, name, mCCP) = studentInfo
print(“Student \(name)'s identification number is \(idNum)”)
if mCCP {
print(“\(name) is a member of Chinese Communist Party”)
} else {
print(“\(name) isn't a member of Chinese Communist Party”)
}
//访问元组方法2
print(“Student \(studentInfo.1)'s identification number is \(studentInfo.0)”)
if studentInfo.2 {
print(“\(studentInfo.1) is a member of Chinese Communist Party”)
} else {
print(“\(studentInfo.1) isn't a member of Chinese Communist Party”)
}
//访问元组方法3
let anotherStudentInfo = (idNum: 60115, name: “Liang Zhang”, mCCP: true)
print(“Student \(anotherStudentInfo.name)'s identification number is \(anotherStudentInfo.idNum)”)
if anotherStudentInfo.mCCP {
print(“\(anotherStudentInfo.name) is a member of Chinese Communist Party”)
} else {
print(“\(anotherStudentInfo.name) isn't a member of Chinese Communist Party”)
}
//定义元组
let studentInfo = (60115, “Liang Zhang”, true)
//访问元组方法1
let (idNum, name, mCCP) = studentInfo
print(“Student \(name)'s identification number is \(idNum)”)
if mCCP {
print(“\(name) is a member of Chinese Communist Party”)
} else {
print(“\(name) isn't a member of Chinese Communist Party”)
}
//访问元组方法2
print(“Student \(studentInfo.1)'s identification number is \(studentInfo.0)”)
if studentInfo.2 {
print(“\(studentInfo.1) is a member of Chinese Communist Party”)
} else {
print(“\(studentInfo.1) isn't a member of Chinese Communist Party”)
}
//访问元组方法3
let anotherStudentInfo = (idNum: 60115, name: “Liang Zhang”, mCCP: true)
print(“Student \(anotherStudentInfo.name)'s identification number is \(anotherStudentInfo.idNum)”)
if anotherStudentInfo.mCCP {
print(“\(anotherStudentInfo.name) is a member of Chinese Communist Party”)
} else {
print(“\(anotherStudentInfo.name) isn't a member of Chinese Communist Party”)
}
5.可选型
//Swift的空值
var studentInSwift: (name: String, idNumber: String, age: Int, reward: String?) = (“Jim”, “37060116”, 19, “Best Student”)
//case 2nd: Tom has no reward
studentInSwift = (“Tom”, “37060115”, 20, nil)
//定义可选类型
var reward: String?
reward = “Best Student”
var bonus: String = “default value”
//字符串拆包
bonus = reward!
//print(“\(bonus)”)
if reward != nil {
bonus = reward!
print(“\(bonus)”)
} else {
print(“reward is nil”)
}
var reward: String?
//可选型绑定
if let reward = reward {
print(“The optional's value is \(reward)”)
} else {
print(“The optional is nil”)
}
var countsOfReward: Int?
countsOfReward = 9
//可选型绑定
if let countsOfReward = countsOfReward {
print(“Counts of reward is \(countsOfReward)”)
} else {
print(“There is no reward record”)
}
var reward: String?
var countsOfReward: Int?
reward = “Best Student”
countsOfReward = 9
//多个可选型绑定
if let reward = reward, let countsOfReward = countsOfReward, countsOfReward > 3 {
print(“reward is \(reward), counts are \(countsOfReward)”)
} else {
print(“no reward or no counts or counts<=3”)
}
// nil聚合运算
var reward: String?
var countsOfReward: Int?
reward = “Best Student”
countsOfReward = nil
var valueOfReward = reward ?? “No Reward”
var valueOfCounts = countsOfReward ?? 0
print(valueOfReward)
print(valueOfCounts)
//练习题5-1
var myHobby: String?
//I like playing soccer
myHobby = “playing soccer”
//I haven't any hobby
myHobby = nil
let parsedInt = Int(“10”)
//parse a string into a int
var parseStringToInt = Int(“10”)
parseStringToInt = Int(“Picasso”)
//练习题5-2
//student's information
var name: String = “Tommy”
var hobby: String?
//force unwrapping
if hobby != nil {
print(“\(name)'s hobby is \(hobby!)”)
} else {
print(“\(name) has no hobby”)
}
var membership: String?
membership = “IEEE senior member”
//optional binding
if let membership = membership {
print(“\(name) is \(membership)”)
} else {
print(“\(name) doesn't join any orgnization!”)
}
hobby = “soccer”
//multiple optional binding
if let hobby = hobby, let membership = membership {
print(“\(name)'s hobby is \(hobby) and is also \(membership)”)
} else {
print(“\(name) has no hobby or doesn't join any orgnization!”)
}
//nil coalescing
var getHobby = hobby ?? “No hobby”
var getMembership = membership ?? “No membership”
hobby = nil
membership = nil
getHobby = hobby ?? “No hobby”
getMembership = membership ?? “No membership”
四、实验结果与分析:
本次实验,主要学习了如何定义常量和变量,以及练习了swift常见数据类型的使用方法,以及如何用不同的方法定义、访问元组等等,在实验中,我主要会因为自己的粗心大意,方法使用不恰当导致运行结果出现误差,检查出错误后,基本所有的实验结果都可以正常运行出来。
五、实验总结:
Swift既是一门高级语言,又是一门低层级语言Swift可以使用map和reduce来很容易创建出自己的高级函数,Swift可以快速完成代码编写,并将他们直接编译为原生二进制可执行文件,这使得性能可以与C语言的编写的程序相媲美。Swift更令人赞叹的是,可以兼顾高低两个层级。将一个数组通过闭包表达式映射到另一个数组所编译得到的汇编码,与直接对一块连续内存进行循环所得到的结果是一致的。2. Swift是一门多范式语言可以使用 Swift来编写面向对象的代码,也可以使用不变量的值,来写纯函数程序。Swift 依然可以使用大部分Objective-C功能,包括消息发送,运行时的类型判定,以及KVO等。Swift还引入了很多Objective-C不具备的特性Swift 拥有泛型,协议,值类型以及闭包等特性,这些特性是函数式风格的很好介绍。
本次课程的学习,我主要学习了如何定义常量与变量、以及swift中常见的数据类型,让我对swift编程语言有了一个基本的认识。在罗老师的带领学习下,我越来越喜欢这IOS门课程,希望在以后的学习中,我可以越来越主动去学习了解更多的知识。本次实验,我主要的学习情况总结如下:
(1)swift 中常见的数据类型
Int 、Float、Double、Character、String
Array、Dictonary、元组类型(Tuple)、可选类型(Optional)
可以看出,数据类型的首字母都是大写的
(2)如何指定变量,常量的数据类型
在常量 变量名后面加上冒号(:)和类型名称
let age:Int = 10
上面代码表示:定义了一个Int类型的变量age 初始值是10
(3)一般来说,没有必要明确指定变量,常量的类型
如果在声明常量、变量时赋了初始值 Swift 以@L_673_5@推断出这个常量、变量的类型
let age = 20
//Swift 会推断出age是Int类型 因为20是个整数
(4)变量初始化
Swift严格要求变量在使用之前必须进行初始化 因为Swift是强类型,而且是类型安全的语言,两个类型不一样是不能相加的等等。