Swift-OOP-继承

2020-11-24  本文已影响0人  守护地中海的花

简易代码

class Animal {
    func speak() {
        print("Animal speak")
    }
    class func eat()  {
        print("Animal eat")
    }
    static func play() {
        print("Animal play")
    }
    subscript(index: Int) -> Int {
        return index
    }
}
var anim :Animal = Animal()
anim.speak()
Animal.eat()
Animal.play()
print(anim[6])

class Cat: Animal {
    override func speak() {
        print("Cat speak")
    }
    override class func eat() {
        print("Cat eat")
    }
    //重写play方法报错 static修饰的方法不行
//    override static play () {
//        print("Cat play")
//    }
    override subscript(index: Int) -> Int {
        return super[index] + 1
    }
}
var cat = Cat()
cat.speak()
Cat.eat()
print(cat[6])

重写属性

class Circle {
    var radius: Int = 0
    var diameter: Int {
        set {
            radius = newValue / 2
        }
        get {
            return radius * 2
        }
    }
    class var radius1: Int {
        get {
            return 20
        }
    }
   static var radius2 = 10
}

var circle = Circle()
circle.radius = 6
print(circle.radius)
print(circle.diameter)
circle.diameter = 6
print(circle.radius)
print(circle.diameter)

class subCircle: Circle {
    override var radius: Int {
        set {
            super.radius = newValue > 0 ? newValue : 0
        }
        get {
            return super.radius * 2
        }
    }
    override class var radius1: Int {
        get {
            return 20
        }
    }
    
}
var subC = subCircle()
subC.radius = -10
print("subCircle",subC.radius)

属性观察器

class Circle {
    var radius: Int = 1
}
class SubCircle : Circle {
    override var radius: Int {
        willSet {
            print("SubCircle willSetRadius",newValue)
        }
        didSet {
            print("SubCircle didSetRadius",oldValue,radius)
        }
    }
}
let circle = SubCircle()
circle.radius = 10

final

上一篇 下一篇

猜你喜欢

热点阅读