编辑代码

// import Foundation
//无参数无返回值的函数
// func showName(){
//     print("你好!罗良夫")
// }
// showName()
// //无参数有返回值
// func showDate() ->String{
//     let dateFormatter = DateFormatter()
//     dateFormatter.dateFormat = "yyyy 年 mm 月 dd 日 HH 时 mm 分 ss 秒"
//     return dateFormatter.string(from:Date())
// }
// var now = showDate()
// print(now)
// //有参数无返回值
// func helloSomeone(name:String){
//     print("\(name)你好,欢迎登录系统!")
// }
// helloSomeone(name:"罗良夫")
// 有参数有返回值
// func add(num1:Int,num2:Int) ->Int{
//     return num1 + num2
// }
// print("124 + 591 =\(add(num1:124,num2:591))")

// //swift可变参数的使用
// func generalIncome(salary:Double...) ->Double{
//     var income:Double = 0.0
//     for tmp in salary{
//         income += tmp
//     }
//     return income
// }
// print("总收入为:\(generalIncome())元")
// print("总收入为:\(generalIncome(salary:1000.05,2846.5,3864.0))元。")

// //多参数时可变参数的使用
// func showLike(name:String,like:String...){
//     print("\(name)的爱好是:",terminator:"")
//     var index = 1
//     for tmp in like{
//         if index == like.count{
//             print("\(tmp).")
//         }else{
//             print(tmp,terminator:"")
//         }
//         index += 1
//     }
// }
// showLike(name:"罗良夫",like:"骑行","羽毛球")


// // Swift参数默认值的使用
// //参数的默认值
// func isLeapFebruary(year:Int = 2022) -> Int{
//     if year % 4 == 0 && year % 100 != 0 || year % 400 == 0{
//         return 29
//     }else{
//         return 28
//     }
// }
// var year = 2024
// var februryDay = isLeapFebruary(year:year)
// print("\(year)\(februryDay == 29 ?"是闰年,2月份有29天.":"不是闰年,2月份有28天.")")
// februryDay = isLeapFebruary()
// print("2022年\(februryDay == 29 ?"是闰年,2月份有29天.":"不是闰年,2月份有28天.")")

// //swift参数标签的使用
// //参数标签
// func showName(user name:String){
//     print("欢迎\(name)登录!")
// }
// showDate(user:"罗良夫")
//参数标签与参数名同名
// func isLeapYear(year:Int){
//     if year % 4 == 0 && year % 100 != 0 || year % 400 != 0{
//         print("\(year)是闰年!")
//     }else{
//         print("\(year)不是闰年!")
//     }
// }
// isLeapYear(year:2022)
// //占位符的使用
// func averageAge(_ age:Int...) ->Double{
//     var sum:Int = 0
//     for tmp in age{
//         sum += tmp
//     }
//     return Double(sum)/Double(age.count)
// }
// print("学生的平均年龄:\(averageAge(18,23,19,20,22))岁。")

// //swift输入输出参数的使用
// func swapValue(num1:inout Int, num2:inout Int){
//     var tmp:Int
//     tmp = num1
//     num1 = num2
//     num2 = tmp
// }
// var num1:Int = 100,num2 = 150
// print("交换前:num1=\(num1),num2=\(num2)")
// swapValue(num1:&num1,num2:&num2)
// print("交换后:num1=\(num1),num2=\(num2)")

// //函数类型
// func add(num1:Int, num2:Int) ->Int{
//     return num1 + num2
// }
// func div(num1:Int, num2:Int) ->Int{
//     return num1 - num2
// }
// var cal:(Int,Int) ->Int = add
//     let res1 = cal(730,35012)
//     print("res1 = \(res1)")
//     cal = div
//     let res2 = cal(730,35012)
//     print("res2 = \(res2)")
// //函数作为参数类型
// func showMsg(user:String,message:String) ->Void{
//     print("\(user)say:\(message)")
// }
// func caller(funcName:(String,String) ->Void,v1:String,v2:String){
//     funcName(v1,v2)
// }



//函数定义1
func mulAdd(mul1:Int,mul2:Int,add:Int) -> Int {
    let result = mul1 * mul2 + 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 mul1 * mul2 + 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)
//函数定义与调用
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")
print(climateTemp)

//函数定义-可变形参
func sum(numbers : Int...) -> Int{
    var result = 0
    for number in numbers {
        result = result + number
    }
    return result
}
var sums = sum(numbers: 1,2,3,4,5,6,7,8,9)
print(sums)
sums = sum(numbers: 10,11,12)
print(sums)

//函数-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)")

//2.闭包
//闭包表达式的定义
let add: (Int, Int) -> Int = { (a, b) in
    return a + b
}
//闭包调用
let result = add(3, 5)
print(result) 
//闭包表达式简写
func sum(a: Int , b: Int, fn: (Int, Int) -> Int){
    print(fn(a,b))
} 
//方式一
sum(a: 30, b: 40, fn: {
    (a:Int, b:Int) -> Int in
    a + b
} ) 
//方式二
sum(a: 40, b: 30, fn: {
    a,b in
    a + b
}) 
//方式三
sum(a: 30, b: 40, fn: {$0 + $1})
//方式四
sum(a: 50, b: 40, fn: + )
//尾随闭包
let numbers = [1, 2, 3, 4, 5]
let mapped = numbers.map { $0 * 2 }
//map 方法获取一个闭包表达式作为其唯一参数。
//数组中的每一个元素调用一次该闭包函数,并返回该元素所映射的值。
//自动闭包
func printIfTrue(_ predicate: @autoclosure () -> Bool) {
    if predicate() {
        print("条件为真")
    }
}
printIfTrue(2 > 1)
//3.结构体
//结构体的定义
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)
//结构体使用
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 (x * x + y * y).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())")

//4.类
//基类
class Student {
    var name = ""
    var age = 0
    var id = ""
    var basicInfo : String {
        return "\(name) is \(age) years old, the id is \(id)"
    }
    func chooseClass(){
        print("\(name) choose a class.")
    }
    func haveClass(){
        print("\(name) have a class.")
    }
}
let theStudent = Student()
theStudent.name = "Tommy"
theStudent.age = 19
theStudent.id = "37060115"
print(theStudent.basicInfo)
//子类
class Graduate : Student {
    var supervisor = ""
    var researchTopic = ""
    func chooseSuperVisor(superVisor:String){
        self.supervisor = superVisor
    }
}
let theGraduate = Graduate()
theGraduate.name = "Sam"
theGraduate.age = 23
theGraduate.id = "SY0602115"
theGraduate.haveClass()
theGraduate.researchTopic = "Graphics"
theGraduate.chooseSuperVisor(superVisor: "Ian")
print("Graduate \(theGraduate.name) is \(theGraduate.age) and the id is \(theGraduate.id), The research topic is \(theGraduate.researchTopic) and supervisor is \(theGraduate.supervisor)")

//子类的子类
class Doctor: Graduate {
    var articles = [String]()
    func publishArticle(article : String){
        articles.append(article)
    }
}
let theDoctor = Doctor()
theDoctor.name = "Pennie"
theDoctor.age = 26
theDoctor.id = "BY0607120"
print(theDoctor.basicInfo)
theDoctor.chooseSuperVisor(superVisor: "Ellis")
print(theDoctor.supervisor)
theDoctor.publishArticle(article: "Petri nets theory")
theDoctor.publishArticle(article: "Process management")
print(theDoctor.articles)
//多态性
class Student {
    var name = ""
    var age = 0
    var id = ""
    var basicInfo : String {
        return "\(name) is \(age) years old, the id is \(id)"
    }
    func chooseClass(){
        print("\(name) choose a class.")
    }
    func haveClass(){
        print("\(name) have a class.")
    }
}
class Graduate : Student {
    var supervisor = ""
    var researchTopic = ""
    override var age : Int {
        didSet {
            print("age is set from \(oldValue) to \(age)")
        }
        willSet {
            print("original age will be set to \(newValue)")
        }
    }
    override var basicInfo : String{
        return super.basicInfo + ", supervisor is \(supervisor), research topic is \(researchTopic)"
    }
    func chooseSuperVisor(superVisor : String){
        self.supervisor = superVisor
    }
    override func chooseClass() {
        print("graduate \(name) choose a class")
    }
}
func sportGameRoster(stu:Student)->String{
    return "Athlete name:\(stu.name),age:\(stu.age),id:\(stu.id)"
}
let studenteTom = Student()
studenteTom.name = "Tom"
studenteTom.age = 19
studenteTom.id = "37060116"
let graduateJim = Graduate()
graduateJim.name = "Jim"
graduateJim.age = 24
graduateJim.id = "SY060218"
let rosterTom = sportGameRoster(stu: studenteTom)
print(rosterTom)
let rosterJim = sportGameRoster(stu: graduateJim)
print(rosterJim)