美文网首页
Swift 继承

Swift 继承

作者: 点滴86 | 来源:发表于2016-08-10 14:38 被阅读5次

    基类

    import UIKit
    
    // 基类
    class Vehicle {
        var currentSpeed = 0.0
        var description: String {
            return "traveling at \(currentSpeed) miles per hour"
        }
        
        func makeNoise() {
            
        }
    }
    
    let SomeVehicle = Vehicle()
    print("Vehicle: \(SomeVehicle.description)")
    

    console log 如下


    定义基类.png

    子类

    // 子类
    class Bicycle: Vehicle {
        var hasBasket = false
    }
    
    let bicycle = Bicycle()
    bicycle.hasBasket = true
    bicycle.currentSpeed = 15.0
    print("Bicycle: \(bicycle.description)")
    
    class Tandem: Bicycle {
        var currentNumberOfPassengers = 0
    }
    
    let tandem = Tandem()
    tandem.hasBasket = true
    tandem.currentNumberOfPassengers = 2
    tandem.currentSpeed = 22.0
    print("Tandem: \(tandem.description)")
    

    console log 如下


    定义子类.png

    重写方法

    // 重写方法
    class Train: Vehicle {
        override func makeNoise() {
            print("Choo Choo")
        }
    }
    
    let train = Train()
    train.makeNoise()
    

    console log 如下


    重写方法.png

    重写计算属性

    // 重写计算属性
    class Car: Vehicle {
        var gear = 1
        override var description: String {
            return super.description + " in gear \(gear)"
        }
    }
    
    let car = Car()
    car.currentSpeed = 25.0
    car.gear = 3
    print("Car: \(car.description)")
    

    console log 如下


    重写计算属性.png

    重写属性监听

    // 重写属性监听
    class AutomaticCar: Car {
        override var currentSpeed: Double {
            didSet {
                gear = Int(currentSpeed / 10.0) + 1
            }
        }
    }
    
    let automic = AutomaticCar()
    automic.currentSpeed = 35.0
    print("AutomaticCar: \(automic.description)")
    

    console log 如下


    重写属性监听.png

    注意: 用final 关键字来阻止重写

    相关文章

      网友评论

          本文标题:Swift 继承

          本文链接:https://www.haomeiwen.com/subject/lhkjsttx.html