2016年6月15日 星期三

SWIFT-多型(polymorphism),Protocol, 整合範例練習

Protocol: 用於定義方法和屬性的名稱藍圖,而不提供實作任何功能。(像契約)

整合範例練習重點:
1. 評估Enum , Struct , Class 使用時機.
2. 練習Protocol & 多型(polymorphism)實作.
3. 練習Class繼承
4. 根據輸入條件(半徑, 長寬, 正方形寬), 計算面積 / 周長

 物件類別圖 - 協助定義相互關係

types.swift 

main.swift & Result 執行結果


[Code程式區 - types.swift]
protocol  ShapeDelegate {
    var area : Double {get}
    var peremeter : Double {get}
    func showInfo()
}

struct Circle : ShapeDelegate {
    var radius : Double
    // Protocol 所定亦需要的實作
    var area : Double {
        // 面積
        return M_PI*pow(radius, 2.0)
    }
    var peremeter : Double {
        // 周長
        return M_PI*radius*2.0
    }
    func showInfo(){
        print("\(self.dynamicType) : \nArea : \(area)\nPeremeter : \(peremeter)")
    }
}

// Global Function
func showShapeInfo(shape : ShapeDelegate){
    print("\(shape.dynamicType) : \nArea : \(shape.area)\nPeremeter : \(shape.peremeter)\n")
}

class Rectangle : ShapeDelegate {
    var width : Double
    var height : Double
    init(width : Double, height : Double){
        self.width = width
        self.height = height
    }
    // Protocol 所定亦需要的實作
    var area : Double {
        return width * height
    }
    var peremeter : Double {
        return (width + height)*2.0
    }
    func showInfo(){
        print("\(self.dynamicType) : \nArea : \(area)\nPeremeter : \(peremeter)")
    }
}

class Square : Rectangle{
    init(width : Double){
        super.init(width: width, height: width)
    }

}


[Code程式區 - main.swift]
let c1 : ShapeDelegate = Circle(radius: 10)
c1.showInfo()
let r1 : ShapeDelegate = Rectangle(width: 6, height: 8)
r1.showInfo()
let s1 : Rectangle = Square(width: 7)
s1.showInfo()
showShapeInfo(c1)
showShapeInfo(r1)

showShapeInfo(s1)


George Huang 烤蕃薯@Taipei 2016

沒有留言: