编辑代码

// 食品类
class Food {
    var name: String
    var price: Double
    var quantity: Int
    
    init(name: String, price: Double, quantity: Int) {
        self.name = name
        self.price = price
        self.quantity = quantity
    }
    
    // 计算原始总价
    func calculateOriginalPrice() -> Double {
        return price * Double(quantity)
    }
    
    // 计算打折后的总价(默认不打折)
    func calculateDiscountedPrice() -> Double {
        return calculateOriginalPrice()
    }
}

// 蔬菜类
class Vegetables: Food {
    override init(name: String, price: Double, quantity: Int) {
        super.init(name: name, price: price, quantity: quantity)
    }
    
    // 计算打九折后的总价
    override func calculateDiscountedPrice() -> Double {
        return calculateOriginalPrice() * 0.9
    }
}

// 水果类
class Fruits: Food {
    override init(name: String, price: Double, quantity: Int) {
        super.init(name: name, price: price, quantity: quantity)
    }
    
    // 计算打八折后的总价
    override func calculateDiscountedPrice() -> Double {
        return calculateOriginalPrice() * 0.8
    }
}

// 肉类类
class Meats: Food {
    override init(name: String, price: Double, quantity: Int) {
        super.init(name: name, price: price, quantity: quantity)
    }
    
    // 计算打七折后的总价
    override func calculateDiscountedPrice() -> Double {
        return calculateOriginalPrice() * 0.7
    }
}

// 创建食品实例
let vegetables1 = Vegetables(name: "西红柿", price: 2.5, quantity: 3)
let fruits1 = Fruits(name: "苹果", price: 4.0, quantity: 2)
let meats1 = Meats(name: "牛肉", price: 30.0, quantity: 1)

// 计算总价
var sum = 0.0
let foodInstances: [Food] = [vegetables1, fruits1, meats1]
for food in foodInstances {
    sum += food.calculateDiscountedPrice()
}

// 打印总价
print("总价:\(sum)")