Initialization

2017-11-08  本文已影响0人  夜雨聲煩_
代码示例

函数继承树关于构造器的继承以及指定构造器和便利构造器的应用。

class Food {
    var name: String
    init(name: String) {
        self.name = name
    }
    //提供一个带有默认值的便利构造器
    convenience init() {
        self.init(name: "[Unnamed]]")
    }
}

let namedMeat = Food.init(name: "Bacon")

class RecipeIngredient: Food {
    var quantity: Int
    init(name: String, quantity: Int) {
        //本类中的属性可以在super.init前面赋值,而父类的属性要在super.init后赋值
        self.quantity = quantity
        super.init(name: name)
    }
    //提供一个便利构造器不指定个数时默认为1
    //此方法实际上重载的是food中的指定构造器
    override convenience init(name: String) {
        self.init(name: name, quantity: 1)
    }
    //和父类中的便利构造器相同,但是不需要override重载
    convenience init() {
        self.init(name: "default", quantity: 0)
    }
}

let oneMysteryItem = RecipeIngredient()
let oneBacon = RecipeIngredient.init(name: "Bacon")
let sixEggs = RecipeIngredient.init(name: "Eggs", quantity: 6)

class AShoppingListItem: RecipeIngredient {
    var purchased = false
    // 使用闭包返回一个只读计算属性
    var description: String {
        var output = "\(quantity) x \(name) "
        output += purchased ? "✔️" : "❌"
        return output
    }
}

var breakfaseList = [AShoppingListItem(), AShoppingListItem.init(name: "Bacon"), AShoppingListItem.init(name: "Eggs", quantity: 6)]
breakfaseList[0].name = "Orange juice"
breakfaseList[0].purchased = true
for item in breakfaseList {
    print("\(item.description)")
}
补充几点
上一篇下一篇

猜你喜欢

热点阅读