Untitled

mail@pastecode.io avatar
unknown
plain_text
11 days ago
1.3 kB
3
Indexable
Never
final class VM {
    func executeSalaryCalculation() {
        var employee: Employee? = Employee(name: "John Doe", baseSalary: 50000, bonus: 5000)
        employee?.setCalculationHandler { salary in
            print("Handler received salary: \(salary)")
        }
        employee?.calculateTotalSalary()
        employee = nil
    }
}

class Employee {
    var name: String
    var baseSalary: Double
    var bonus: Double
    var calculationHandler: ((Double) -> Void)?

    init(name: String, baseSalary: Double, bonus: Double) {
        self.name = name
        self.baseSalary = baseSalary
        self.bonus = bonus
    }

    func calculateTotalSalary() {
        let handler = self.calculationHandler!
        DispatchQueue.main.async {
            DispatchQueue.main.sync {
                let totalSalary = self.baseSalary + self.bonus
                handler(totalSalary)
            }
        }
    }

    func setCalculationHandler(handler: @escaping (Double) -> Void) {
        self.calculationHandler = { [weak self] salary in
            self?.handleSalaryCalculation(salary)
        }
    }

    private func handleSalaryCalculation(_ salary: Double) {
        print("Calculated salary for \(name) is \(salary)")
    }

    deinit {
        print("\(name) is being deinitialized")
    }
}
Leave a Comment