swift繼承

weixin_33859844發表於2017-06-26
1、屬性的繼承

子類可以繼承父類的屬性,包括儲存屬性、計算屬性和型別屬性

class Person{
    //儲存屬性
    var age = 20
    //計算屬性
    var description: String{
        return "我現在\(self.age)歲了"
    }
    //型別屬性
    static var kind = "Chinese"
}
class Teacher : Person{}
let teacher = Teacher()
print(teacher.age,teacher.description,"\(Teacher.kind)")

控制檯:

20 我現在20歲了 Chinese
2、屬性觀察器的繼承
class Person{
    //儲存屬性
    var age = 20{
        willSet{
            print("age即將被賦值\(newValue)")
        }
        didSet{
            if(age > oldValue){
                print("新賦值的值比原來的大")
            }else{
                print("新賦值的值比原來的小")
            }
        }
    }
}
class Teacher : Person{}
var t:Teacher = Teacher()
t.age = 19

控制檯:

age即將被賦值19
新賦值的值比原來的小
3、下標指令碼的繼承
class Person{
    subscript (index:Int) -> String{
        switch index{
        case 1:
            return "1"
        case 2:
            return "2"
        case 3:
            return "3"
        default:
            return "default"
        }
    }
}
class Teacher : Person{}
let teacher = Teacher()
print(teacher[1],teacher[6])

控制檯:

1 default
4、方法的繼承

包括物件方法和類方法

class Person{
    func description(){
        print("我是Person的方法")
    }
}
class Teacher : Person{}
let teacher = Teacher()
teacher.description()

控制檯:

我是Person的方法
5、增加新屬性和方法
class Person{
    subscript (index:Int) -> String{
        switch index{
        case 1:
            return "1"
        case 2:
            return "2"
        case 3:
            return "3"
        default:
            return "default"
        }
    }
    func run(){
        print("Person is running")
    }
}
class Teacher : Person{
    let age = 15
    func walk(){
        print("Teacher is walking")
    }
}
let person = Person()
let teacher = Teacher()
person.run()
teacher.walk()
print(teacher.age)

控制檯:

Person is running
Teacher is walking
15

相關文章