一、 实验目的:
- 掌握Swift枚举
- 理解Swift结构体的特点
- 理解Swift属性
- 掌握Swift函数
- 掌握Swift泛型
二、实验原理:
1.枚举的定义
2.枚举类型的原始值与关联值的区别
3.结构体的定义
4.函数的定义格式
5.函数的类型
6.Swift泛型的定义
三、实验步骤及内容:
1.枚举
//枚举的定义
enum MonthFull {
case January
case February
case March
case April
case May
case June
case July
case August
case September
case October
case November
case December
}
//枚举的定义
enum Month {
case January,February,March,April,May,June, July,August,September,October,November,December
}
//枚举赋值
var thisMonth = Month.August
var nextMonth : Month = .September//类型声明后,赋值过程中可以省略枚举类型名
//读取枚举值
switch nextMonth {
case .January, .February, .March, .April, .May, .June : print(“It belongs first half year”)
default : print(“It belongs second half year”)
}
//定义原始值
enum Car:Int{
case truck = 0
case sportsCar
case SUV
case MPV
case limo
}
//访问原始值
var myCar=Car.SUV
var rawValue=myCar.rawValue
myCar=Car.limo
rawValue=myCar.rawValue
let yourCar = Car(rawValue:1)
//关联值
enum transportFee {
case byAir(Int,Int,Int)
case byCar(Int,Int)
case byTrain(Int)
}
//关联值的赋值
var fromShanghaiToBeijing = transportFee.byTrain(299)
fromShanghaiToBeijing = .byAir(800, 230, 50)
//访问关联值
switch fromShanghaiToBeijing {
case .byAir(let ticketFee, let tax, let insurance) : print(“The sum fee is (ticketFee+tax+insurance) by air”)
case .byCar(let fuelFee, let highwayFee) : print(“The sum fee is (fuelFee+highwayFee) by car”)
case .byTrain(let ticketFee) : print(“The sum fee is (ticketFee) by Train”)
}
//可选型的实现
var hobby: String?
hobby = “Basketball”
hobby = nil
switch hobby {
case .none:
print(“No hobby”)
case .some(let hobbyName):
print(“Hobby is (hobbyName)”)
}
//练习题1
enum Direction {
case East
case South
case West
case North
}
func adjacentCity(direction: Direction) -> String {
switch direction {
case .East: return “Sanhe”
case .West: return “Baoding”
case .South: return “Tianjin”
case .North: return “Zhangjiakou”
}
}
let northNeighbour = adjacentCity(direction: .North)
print(“The northern city is (northNeighbour)”)
//练习题2
enum Direction: Int{
case East=0
case South
case West
case North
}
let currentDirection = Direction.North
print(“The raw value of North is (currentDirection.rawValue)”)
//练习题3
enum Direction: String{
case East
case South
case West
case North
}
let currentDirection = Direction.North
print(“The raw value of North is (currentDirection.rawValue)”)
//练习题4
enum OperationFeedback {
case Done(currentBalance: Int)
case Fail(warningInfo: String)
}
var balanceOfATM = 10000
func withdrawFromATM(amount: Int) -> OperationFeedback{
if balanceOfATM >= amount {
balanceOfATM -= amount
return .Done(currentBalance: balanceOfATM)
} else {
return .Fail(warningInfo: “Balance is not enough!”)
}
}
var getMoney = withdrawFromATM(amount: 1288)
switch getMoney {
case .Done(let currentBalance):
print(“Operation is successful. The current balance is (currentBalance)”)
case .Fail(let warningInfo):
print(warningInfo)
}
2.结构体
//结构体的定义
struct Book {
var name = “”
var price = 0
var category = “common”
func description() {
print(“(name)'s price is (price), category is (category)”)
}
}
//结构体实例化
var theBook = Book(name: “Life of Pi”, price: 62, category: “adventure”)
print(“(theBook.name)'s category is (theBook.category) and price is (theBook.price)RMB”)
//访问结构体方法
let newBook = Book(name: “Life of Pi”, price: 62, category: “adventure”)
newBook.description()
//值类型
var anotherBook = theBook
print(theBook)
print(anotherBook)
anotherBook.category = “history”
anotherBook.price = 136
anotherBook.name = “Empiror Kangxi”
print(theBook)
print(anotherBook)
//练习题5
struct Coordinate {
let x : Double
let y : Double
}
struct Line {
let startPoint: Coordinate
let endPoint: Coordinate
func length() -> Double {
let x = startPoint.x - endPoint.x
let y = startPoint.y - endPoint.y
return (xx + yy).squareRoot()
}
}
let pointA = Coordinate(x: 1, y: 2)
let pointB = Coordinate(x: 3, y: 6)
let lineAB = Line(startPoint: pointA, endPoint: pointB)
print(“The length of line AB is (lineAB.length())”)
enum stageOfWashingMachine {
case ready
case watering
case washing
case dewatering
case drying
}
3.函数
//函数定义1
func mulAdd(mul1:Int,mul2:Int,add:Int) -> Int {
let result = mul1mul2 + add
return result
}
var result = 0
result = mulAdd(mul1: 3, mul2: 5, add: 3)
print(“The result of mulAdd is \(result)”)
//函数定义-无参数
func mulAdd() -> Int {
let mul1,mul2,add : Int
mul1 = 3
mul2 = 5
add = 3
return mul1mul2 + add
}
result = mulAdd()
print(“The result of mulAdd is \(result)”)
//函数定义-无返回值
func mulAdd(mul1:Int,mul2:Int,add:Int){
print(“The result of mulAdd is \(mul1*mul2 + add)”)
}
mulAdd(mul1:3, mul2:5, add:3)
//练习题6
func printCapitalInfo(name: String, country: String, population: Int) {
print(“\(name) is the capital of \(country) and its population is \(population) million.”)
}
printCapitalInfo(name: “Beijing”, country: “China”, population: 23)
func calculateCapitalInfo(name: String, country: String, population: Int) -> (String, Int) {
let capitalInfo = name + “ is the capital of “ + country + “ and its population is “ + String(population) + “ million.”
let lengthOfInfo = capitalInfo.count
return (capitalInfo, lengthOfInfo)
}
let capitalInfo = calculateCapitalInfo(name: “Beijing”, country: “China”, population: 23)
print(capitalInfo)
//函数定义-返回多个值
func climate(city:String)->(averageTemperature:Int,weather:String,wind:String) {
var averageTemperature : Int
var weather,wind : String
switch city {
case “beijing”: averageTemperature = 25;weather = “dry”;wind = “strong”
case “shanghai”: averageTemperature = 15;weather = “wet”;wind = “weak”
default : averageTemperature = 10; weather = “sunny”; wind = “normal”
}
return (averageTemperature,weather,wind)
}
var climateTemp = (0, ““, ““)
climateTemp = climate(city: “beijing”)
//函数定义-可变形参
func sum(numbers : Int…) -> Int{
var result = 0
for number in numbers {
result = result + number
}
return result
}
sum(numbers: 1,2,3,4,5,6,7,8,9)
sum(numbers: 10,11,12)
//函数-inout参数
func swap(a:inout Int, b:inout Int) {
let temp = a
a = b
b = temp
}
var a = 5
var b = 6
swap(a: &a, b: &b)
print(“a is \(a)”)
print(“b is \(b)”)
//练习题7
//1
func computeMultiply() -> Int {
var result = 1
for i in 1…10 {
result *= i
}
return result
}
var result = 0
result = computeMultiply()
//2
func printMultiply() {
var result = 1
for i in 1…10 {
result *= i
}
print(“10! = \(result)”)
}
printMultiply()
//3
func computeMultiply(multipliers : Int…) -> Int {
var result = 1
for i in multipliers {
result *= i
}
return result
}
let product = computeMultiply(multipliers: 1,3,5,7,9)
//4
var numbers = [15,3,90,2,0,8,10,12]
print(“unsorted array is: \(numbers)”)
func sortArray(intArray: inout [Int]) {
intArray.sort()
}
sortArray(intArray: &numbers)
print(“sorted array is: \(numbers)”)
//5
var printAction : ()->() = printMultiply
var mathOperation: (Int…)->Int = computeMultiply
printAction()
let returnValue = mathOperation(2,4,8)
//6
func multiply(a: Int, b: Int) -> Int {
return a * b
}
func divide(a: Int, b: Int) -> Int {
return a / b
}
func printMathOperation(operation: (Int, Int)->Int, a: Int, b: Int) {
let result : Int
if a > b {
result = operation(a,b)
} else {
result = operation(b,a)
}
print(“the result of operation between \(a) and \(b) is \(result)”)
}
printMathOperation(operation: multiply, a: 28, b: 5)
printMathOperation(operation: divide, a: 28, b: 5)
//7
func multiplyOrDivideOperation(op: String) -> (Int, Int)->Int {
if op == “Multiply” {
return multiply
} else {
return divide
}
}
var operation = multiplyOrDivideOperation(op: “Multiply”)
printMathOperation(operation: operation, a: 9, b: 108)
operation = multiplyOrDivideOperation(op: “Divide”)
printMathOperation(operation: operation, a: 9, b: 108)
//函数类型-有参数有返回值
func add(a: Int,b: Int) ->Int{
return a+b
}
//函数类型-无参数无返回值
func helloWorld() {
print(“Hello world!”)
}
//函数类型变量
var mathOperation : (Int,Int)->Int = add
var sayOperation : ()->() = helloWorld
mathOperation(5,6)
sayOperation()
var operation = add
operation(6, 7)
//函数类型的参数
func add(a: Int,b: Int) ->Int{
return a + b
}
func sub(a: Int,b: Int) ->Int{
return a - b
}
func printResult(operation: (Int,Int)->Int, a:Int, b:Int) {
let result : Int
if a>b {
result = operation(a,b)
} else {
result = operation(b,a)
}
print(“the result is \(result)”)
}
printResult(operation: sub, a: 3, b: 9)
//函数类型的返回值
func mathOperation(op: String) -> (Int,Int)->Int {
if op == “sub” {
return sub
}else {
return add
}
}
let result = mathOperation(op: “sub”)
result(6,3)
//嵌套函数
func printResult(a:Int, b:Int) {
func add(a: Int,b: Int) ->Int{
return a + b
}
func sub(a: Int,b: Int) ->Int{
return a - b
}
let result : Int
if a>b {
result = sub(a: a, b: b)
} else {
result = add(a: b, b: a)
}
print(“the result is \(result)”)
}
printResult(a: 6, b: 3)
//练习题8
func multiplyOrDivideOperation(op: String, num1: Int, num2: Int) -> Int {
func multiply(a: Int, b: Int) -> Int {
return a * b
}
func divide(a: Int, b: Int) -> Int {
return a / b
}
if op == “Multiply” {
return multiply(a:num1, b:num2)
} else {
if num1 > num2 {
return divide(a:num1,b:num2)
} else {
return divide(a:num2,b:num1)
}
}
}
var result = multiplyOrDivideOperation(op: “Divide”, num1:5, num2:15)
4.泛型
//泛型函数
func swap2Int( a : inout Int, b : inout Int) {
let temp = a
a = b
b = temp
}
var a = 3
var b = 5
swap(&a, &b)
print(“a is (a), b is (b)”)
func swap2String( a : inout String, b : inout String) {
let temp = a
a = b
b = temp
}
var c = “Hello”
var d = “world”
print(“© (d)”)
swap(&c, &d)
print(“© (d)”)
print(“a is (a), b is (b)”)
print(“c is ©, d is (d)”)
func swap2Element( a : inout T, b : inout T){
let temp = a
a = b
b = temp
}
swap2Element(a: &a, b: &b)
swap2Element(a: &c, b: &d)
print(“a is (a), b is (b)”)
print(“c is ©, d is (d)”)
//泛型类
class Car {
var brand: String
init(brand: String) {
self.brand = brand
}
}
class Bike {
var speed: Int
init(speed: Int) {
self.speed = speed
}
}
class Driver {
var name: String
var vehicle: Vehicle
init(name: String, vehicle: Vehicle) {
self.name = name
self.vehicle = vehicle
}
}
let porscheCar = Car(brand: “Porsche”)
let driverTom = Driver(name: “Tom”, vehicle: porscheCar)
let giantBike = Bike(speed: 50)
let driverSam = Driver(name: “Sam”, vehicle: giantBike)
//练习题9
func swap2Element<T, U>(a: T, b: U) -> (U, T) {
return (b, a)
}
let theTuple = swap2Element(a: 33, b: “Jay”)
print(theTuple)
//练习题10
class Person<T, U> {
var name: String
var weight: T
var height: U
init(name: String, weight: T, height: U) {
self.name = name
self.weight = weight
self.height = height
}
func description(){
print(“(name)'s weight is (weight) and height is (height)”)
}
}
let jennie = Person(name: “Jennie”, weight: 45, height: 160)
let jack = Person(name: “Jack”, weight: 69.2, height: 173)
let sam = Person(name: “Sam”, weight: 88.8, height: “Unknow”)
jennie.description()
jack.description()
,sam.description()
四、实验结果与分析:
枚举在Swift中是 first-class types。与C,Objective-C中的枚举相比,Swift中枚举功能更强大。它支持很多只有类才有的特性,如: Properties, Methods, Initialization, Extensions, Protocols.
枚举简单的说也是一种数据类型,只不过是这种数据类型只包含自定义的特定数据,它是一组有共同特性的数据的集合。
Swift 的枚举类似于 Objective C 和 C 的结构,枚举的功能为:
它声明在类中,可以通过实例化类来访问它的值。
枚举也可以定义构造函数(initializers)来提供一个初始成员值;可以在原始的实现基础上扩展它们的功能。
可以遵守协议(protocols)来提供标准的功能。
五、实验总结:
本次课程的学习,我主要学习了Swift枚举&结构体&函数&泛型让我对swift编程语言有了一个基本的认识。在罗老师的带领学习下,我越来越喜欢这IOS门课程,希望在以后的学习中,我可以越来越主动去学习了解更多的知识。
教师评阅: