Swift实验(三)

编写代码,实现以下要求:
1)实现Person类,具有firstName, lastName,age,gender等存储属性,fullName计算属性,其中gender是枚举类型(male,female)
2)具有指定初始化器和便利初始化器,指定初始化器使用required关键字修饰;
3)Person具有work方法,输出“Person XXX is working”
4)从Person分别派生Teacher类和Student类
5)Teacher类重写work方法,输出“Teacher XXX is teaching”
6)Student类增加学号(StuID)、C语言成绩(cScore)、C++语言成绩(cppScore)和数据结构成绩(dataStruct)四个存储属性
7)Student类重写work方法,输出“Student XXX is Learning”
8)Student类定义下标,分别返回C语言、C++语言和数据结构成绩
9)创建Person、Teacher、Student对象,别分调用work方法,输出Student下标值

enum Gender{
    case male
    case famale
}

class Person {
    var firstName:String
    var lastName:String
    var age:Int
    var gender:Gender
    var fullName:String{
        return firstName+lastName
    }
    
     init(firstName:String,lastName:String,age:Int,gender:Gender) {
        self.firstName=firstName
        self.lastName=lastName
        self.age=age
        self.gender=gender
    }
    
    convenience init(str:String){
        self.init(firstName:str, lastName:str , age:0 , gender:Gender.male)
    }
    
    func work()  {
        print("Person \(fullName) is working")
    }
}

class Teacher: Person {
    override func work() {
        print("Teacher \(fullName) is working")
    }
}
class Student: Person {
    var StuID:UInt
    var cScore:Int
    var cppScore:Int
    var dataStruct :Int
    init(firstName:String,lastName:String,age:Int,gender:Gender,Id:UInt,c:Int,cpp:Int,data:Int) {
        self.StuID=Id
        self.cScore=c
        self.cppScore=cpp
        self.dataStruct=data
        super.init(firstName:
            firstName,lastName:lastName,age:age,gender:gender)
    }
    override func work() {
        print("Student \(fullName) is working")
    }
    subscript( sideIndex:Int) ->Int
    {
        switch sideIndex {
        case 1:return cScore
        case 2:return cppScore
        case 3:return dataStruct
        default:return -1
        }
    }
}
var p=Person(firstName: "harry", lastName: "bob", age: 18, gender:Gender.male)
p.work()
var t=Teacher(firstName: "lucy", lastName: "king", age: 20, gender: Gender.famale)
t.work()
var s=Student(firstName: "he", lastName: "thrinity", age: 20, gender: Gender.male, Id: 201601, c: 100, cpp: 99, data: 98)
s.work()
print("csocre:\(s[1])")
print("cppsocre:\(s[2])")
print("datasocre:\(s[3])")

你可能感兴趣的:(Swift,swift)