2019年6月17日 星期一

property


import UIKit

struct FixedLengthRange{
    var firstValue:Int;
    let length:Int;
}
var rangeOfThreeItems = FixedLengthRange(firstValue: 0, length: 3)
rangeOfThreeItems.firstValue = 6;

let rangeOfFourItems = FixedLengthRange(firstValue: 0, length: 4);
//需內外都是var才可變更值
//rangeOfFourItems.firstValue = 6;

//lazy store property
class DataImporter{
    var filename = "data.txt"
}
class DataManager{
    lazy var importer = DataImporter();
    var data = [String]()
}
let manager = DataManager();
manager.data.append("Some Data");
manager.data.append("Some more data");
print(manager.importer.filename);

//computed property
struct Student{
    let name:String;
    var math:Int;
    var chinese:Int;
    var english:Int;
    //computed property語法,一定要給資料類型,每呼叫一次sum,就get math + chinese + english
    var sum:Int{
        get{
            return math + chinese + english
        }
    }
    //computed property語法,一定要給資料類型,每呼叫一次average就get Double(sum) / 3.0
    var average:Double{
        get{
            return Double(sum) / 3.0
        }
    }
}
var stu1 = Student(name: "Robert", math: 78, chinese: 67, english: 90);
print("stu1 的 sum 是:\(stu1.sum)");
print("stu1 的 average 是:\(stu1.average)");

//computed property,set
struct Point{
    var _x = 0;
    var _y = 0;
    var x:Int{
        get{
            print("取出x");
            return _x;
        }
        set(newV){
            print("存入值:\(newV)");
            _x = newV;
        }
    }
    var y:Int{
        get{
            print("取出y");
            return _y;
        }
        set(newV){
            print("存入值:\(newV)");
            _y = newV;
        }
    }
}
var point1 = Point(_x: 3, _y: 5);
print("\(point1.x)");
point1.x = 10;
print("\(point1.x)");

沒有留言:

張貼留言