2019年7月10日 星期三

Class Inheritance and Initialization

指定初始化
designated initializer:一個class至少一個
語法:
init(parameters){

}
便利初始化
convenience initializer:可有可無
語法:
convenience init(parameters){

}

import UIKit

class Vehicle {
    var numberOfWheels = 0;
    var description: String {
        return "\(numberOfWheels) wheel(s)";
    }
}
let vehicle = Vehicle();
print(vehicle.description);

class Bicycle:Vehicle{
    override init(){
        super.init();
        numberOfWheels = 2;
    }
}
let bicycle = Bicycle();
print("Bicycle:\(bicycle.description)");

class Hoverboard:Vehicle{
    var color:String;
    init(color:String) {
        self.color = color;
        super.init();
    }
    override var description: String{
        return "\(super.description) in a beautiful \(color)";
    }
}
let hoverboard = Hoverboard(color: "silver");
print("Hoverboard:\(hoverboard.description)");

//自動繼承
class Food{
    var name:String;
    init(name:String) {
        self.name = name;
    }
    convenience init(){
        self.init(name:"[noName]");
    }
}
let nameMeat = Food(name: "Bacon");
let mysteryMeat = Food();
class RecipeIngredient:Food{
    var quantity:Int;
    init(name:String, quantity:Int){
        self.quantity = quantity;
        super.init(name: name);
    }
    override convenience init(name: String) {
        self.init(name:name, quantity:1);
    }
}
let oneMySteryItem = RecipeIngredient();
let oneBacon = RecipeIngredient(name: "Bancon");

let sixEggs = RecipeIngredient(name: "Eggs", quantity: 6);

沒有留言:

張貼留言