2014/06/09

Swift Setter and Getter

Setter:僅可以設定非本身的值,因為尚未分配到屬性
Getter:用於回傳值


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

//return Array to Integer
class CY{
    var bmi:Float = 0.0
    var cm:Float = 0.0
    var kg:Float{
        set{bmi = newValue/(cm*cm)}
        get{return bmi * cm * cm}
    }
    
    init(bmi:Float, cm:Float){
        self.bmi = bmi
        self.cm = cm
    }
}

var fatter = CY(bmi:29.0, cm:1.78)
println(fatter.kg)

fatter.kg = 130
println(fatter.bmi)


執行結果: