2016年6月15日 星期三

SWIFT-多型(polymorphism)範例練習

透過此 多型(polymorphism)範例練習,來練習如何輕鬆達成薪資系統的三件事-實作範例。
1. 計算每個員工獎金紅利判定方法.
2. 計算每個員工需要繳的稅金利率.
3. 如何透過異質集合(Checking Thype) 來輕鬆計算所有員工的薪資總和. 

Swift 實作
types.swift

main.swift

[Code程式區 - types.swift]
// 計算員工拿獎金
func getBouns(e : Employee) {
    // 特例處理, 子孫類別先判對, 順序很重要
    if e is Manager{
        print("+1000")
        let m1 : Manager = e as! Manager
        print(m1.dept ?? "?")
    } else if e is Employee {
        print("+500")
    }
}

// 計算員工需要繳的稅
func getTax(e : Employee) {
    let totalY = e.salary * 14
    if totalY < 800_000 {
        print("Your tax is : 5%")
    } else {
        print("Your tax is : 12%")
    }
}

class Employee {
    var name : String?
    var address : String?
    var salary : Int = 20000    // 假設底薪28000-
    func showInfo() {
        print("\(name ?? "Noname") lives in \(address ?? "somewhere")")
    }
}

class Manager: Employee {
    var dept : String?
    override func showInfo() {
        print("\(name ?? "Noname") a manager of \(dept ?? "???"), Lives in \(address ?? "somewhere")")
    }
}

class Engineer : Employee{
    

}

[Code程式區 - main.swift]
var m1 = Manager()
m1.name = "George"
m1.address = "Taipei"
m1.dept = "Engineer" // 繼承後, 客製化增加的
m1.salary = 60000
m1.showInfo()

// SWIFT-多型(polymorphism)範例測試, (Protocol 也會再一次碰到.)
var e : Employee = Manager()
e.name = "Frank"
e.address = "Tainan"
let m2 = e as? Manager  // e轉化它的型別成為Manager
m2?.dept = "IT2"
e.showInfo()    // 此時是呼叫執行實體Manager.showInfo()

var e1 : Employee = Employee()
e.name = "Frank"
e.address = "Tainan"
e.showInfo()    // 此時是呼叫執行實體Manager.showInfo()

var e2 : Employee = Employee()
e.name = "Sam"
e.address = "Tainan"
e.showInfo()    // 此時是呼叫執行實體Manager.showInfo()

var e3 : Engineer = Engineer()
e3.name = "George"
e3.address = "Taipei"
e3.showInfo()

// 多型應用-異質集合(Checking Thype) (抓出共通性來進行運作)
var employee : [Employee] = [m1, e1, e2, e3]
var total = 0
for e in employee {
    total += e.salary
}
print("TOT: \(total)")

getTax(m1)
getTax(e1)

getTax(e2)


George Huang 烤蕃薯@Taipei 2016

沒有留言: