编辑代码

// 食品类
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 calculateTotalPrice() -> Double {
        return price * Double(quantity)
    }
    
    func calculateDiscountedPrice(discount: Double) -> Double {
        return calculateTotalPrice() * discount
    }
}

// 蔬菜类
class Vegetables: Food {
    override init(name: String, price: Double, quantity: Int) {
        super.init(name: name, price: price, quantity: quantity)
    }
    
    override func calculateTotalPrice() -> Double {
        return super.calculateTotalPrice()
    }
    
    override func calculateDiscountedPrice(discount: Double) -> Double {
        return super.calculateDiscountedPrice(discount: 0.9)
    }
}

// 水果类
class Fruits: Food {
    override init(name: String, price: Double, quantity: Int) {
        super.init(name: name, price: price, quantity: quantity)
    }
    
    override func calculateTotalPrice() -> Double {
        return super.calculateTotalPrice()
    }
    
    override func calculateDiscountedPrice(discount: Double) -> Double {
        return super.calculateDiscountedPrice(discount: 0.8)
    }
}

// 肉类类
class Meats: Food {
    override init(name: String, price: Double, quantity: Int) {
        super.init(name: name, price: price, quantity: quantity)
    }
    
    override func calculateTotalPrice() -> Double {
        return super.calculateTotalPrice()
    }
    
    override func calculateDiscountedPrice(discount: Double) -> Double {
        return super.calculateDiscountedPrice(discount: 0.7)
    }
}

// 创建实例并计算总价
var vegetables = Vegetables(name: "青菜", price: 2.5, quantity: 3)
var fruits = Fruits(name: "苹果", price: 5.0, quantity: 2)
var meats = Meats(name: "牛肉", price: 20.0, quantity: 1)

var sum = vegetables.calculateTotalPrice() + vegetables.calculateDiscountedPrice(discount: 0.9) +
          fruits.calculateTotalPrice() + fruits.calculateDiscountedPrice(discount: 0.8) +
          meats.calculateTotalPrice() + meats.calculateDiscountedPrice(discount: 0.7)

print("总价:\(sum)")
``