2014/06/08

Swift class and override



//
//  main.swift
//  test
//
//  Created by CYFang on 6/6/14.
//  Copyright (c) 2014 CYFang. All rights reserved.
//

//return Array to Integer
class Shape{
    var height:Double = 0.0
    var width:Double = 0.0
    
    init(){}
    
    init(height:Double){
        self.height = height
    }
    
    init(height:Double, width:Double){
        self.height = height
        self.width = width
    }
    

    func getArea() -> Double{
        return 0.0
    }
    
}

class Rectangle:Shape{
    init(height: Double, width: Double) {
        super.init(height:height, width:width)
    }
    
    override func getArea() -> Double{
        return self.width * self.height
    }
}

class Triangle:Shape{
    var upper:Double = 0.0
    
    init(height: Double, upper : Double) {
        super.init(height:height)
        self.upper = upper
    }
    
    override func getArea() -> Double{
        return (self.upper * self.height)/2
    }
}


class Keystone:Shape{
    var upper:Double = 0.0
    var lower:Double = 0.0
    
    init(height : Double, upper : Double, lower : Double){
        super.init(height : height)
        self.upper = upper
        self.lower = lower
    }
    
    override func getArea() -> Double{
        return ((self.lower + self.upper) * self.height) / 2
    }
}

class Circle:Shape{
    let pi:Double = 3.14
    var r = 0.0
    
    init(heigth : Double){
        super.init(height : heigth)
        self.r = heigth/2
    }
    
    override func getArea() -> Double{
        func pow(x:Double, y:Double) -> Double{
            var sum:Double = 1.0
            
            for index in 1...y{
                sum*=x
            }
            return sum
        }

        var sum = pow(self.r, 2.0)
        return sum * self.pi
    }

    
}

var mRectangle = Rectangle(height : 10, width : 10)
println(mRectangle.getArea())

var mTriangle = Triangle(height : 10, upper : 10)
println(mTriangle.getArea())

var mKeystone = Keystone(height: 5, upper: 4, lower: 6)
println(mKeystone.getArea())

var mCircle = Circle(heigth: 6)
println(mCircle.getArea())


執行結果: