编辑代码

//基类
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)