首页 > 其他 > 详细

swift 继承相关

时间:2014-06-18 19:45:04      阅读:285      评论:0      收藏:0      [点我收藏+]

class Vehicle {

    var numberOfWheels: Int

    var maxPassengers: Int

    

    func description() -> String {

        return "\(numberOfWheels) wheels; up to \(maxPassengers) passengers"

    }

    

    init() {

        numberOfWheels = 1;

        maxPassengers = 3;

    }

}

 

class Bicycle: Vehicle {

    init() {

        super.init();

        numberOfWheels = 2;

    }

}

 

 

class Tandem: Bicycle {

    init() {

        super.init();

        maxPassengers = 2;

    }

    

}

 

//override func

class Car : Vehicle {

    var speed : Double = 0.0;

    init() {

        super.init()

        maxPassengers = 5

        numberOfWheels = 4;

    }

    override func description() -> String {

        return super.description() + ";" + "speed at \(speed) mph";

    }

}

 

//override properties

class SpeedLimit : Car {

    override var speed: Double {

    get {

        return super.speed

    }

    set {

        super.speed = max(newValue, 40.0)

    }

    }

}

 

let limit = SpeedLimit();

limit.speed = 220.0

 

println("LimitSpeed:\(limit.description())")

 

//重写属性观察器

class AutomaticCar: Car {

    var gear = 1;

    override var speed: Double {

    didSet {

        gear = Int(speed/10) + 1

    }

    }

    override func description() -> String {

        return super.description() + " in gead at \(gear)";

    }

    

}

let automaticCar = AutomaticCar()

automaticCar.speed = 50.0

println(automaticCar.description())

swift 继承相关,布布扣,bubuko.com

swift 继承相关

原文:http://www.cnblogs.com/blogszixin/p/3790622.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!