#學習筆記#Swift中Class的聲明與運用

import Foundation

class NamedShape {
    var numberOfSides: Int = 0
    var name: String

    init(name: String) {
        self.name = name
    }

    func simpleDescription() ->String {
        return "A shape with \(numberOfSides) sides."
    }
}

// 注意這裏的對象初始,須要傳遞name的屬性數值進去
// 初始的時候必定要寫上「name:「,不然編譯器會認爲沒有進行初始化工做
var shape = NamedShape(name: "Bob")

// 下面是繼承類的聲明與使用
class Square: NamedShape {
    var sideLength: Double

    init(sideLength: Double, name: String) {
        self.sideLength = sideLength
        // 因爲name屬性是經過父類初始函數初始化的
        // 因此必須調用父類的init方法初始化name屬性
        super.init(name: name)
        // 能夠直接使用父類屬性
        numberOfSides = 4
    }

    func area() -> Double {
        return sideLength * sideLength
    }

    // 重載父類方法,必定要寫明override,不然編譯器會報錯
    override func simpleDescription() ->String {
        return "A square with sides of length \(sideLength)."
    }
}

let test = Square(sideLength: 5.2, name: "my test squre")
println(test.area())
println(test.simpleDescription())

如下是getter和setter的用法示例ide

class EquilateralTriangle: NamedShape {
    var sideLength: Double = 0.0

    init(sideLength: Double, name: String) {
        self.sideLength = sideLength
        super.init(name: name)
        numberOfSides = 3
    }

    var perimeter: Double {
    get {
        return 3.0 * sideLength
    }

    set {
        sideLength = newValue / 3.0
    }
    }

    override func simpleDescription() ->String {
        return "An quilateral triagle with side of length \(sideLength)"
    }
}

var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")
println(triangle.perimeter)
triangle.perimeter = 9.9
println(triangle.sideLength)

如下是介紹類模塊中willSet和didSet的用法,這部分比較特別
willSet能夠在設置新的屬性值以前運行,下面的示例是保證triangle和square的sideLength始終保持相等函數

class TriangleAndSquare {
    var square: Square {
    willSet {
        triangle.sideLength = newValue.sideLength
    }
    }

    var triangle: EquilateralTriangle {
    willSet {
        square.sideLength = newValue.sideLength
    }
    }

    init(size: Double, name: String) {
        square = Square(sideLength: size, name: name)
        triangle = EquilateralTriangle(sideLength: size, name: name)
    }
}

var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape")
println(triangleAndSquare.square.sideLength)
println(triangleAndSquare.triangle.sideLength)
// 若是是直接改變square中的sideLength的值,那麼triangle中的sideLength是不會發生變化的
triangleAndSquare.square = Square(sideLength: 50, name: "larger square")
println(triangleAndSquare.triangle.sideLength)

類和結構體的主要區別是,結構體是值傳遞(依靠值的複製進行代碼內部的傳遞),類是引用傳遞ui

相關文章
相關標籤/搜索