屬性&方法 Property & Method


標籤

儲存屬性(stored property)

不管在類別或結構內的變數常數皆為儲存屬性
struct number {
    var data1: Int
    let data2: Int
}
var NUMBER = number(data1: 100, data2: 100)
print("\(number1.data1), \(number1.data2)")
NUMBER.data1 = 200
print("\(number1.data1), \(number1.data2)")
  • 輸出結果
    100, 100
    200, 100
    

計算屬性(computed property)

  • 透過getter、setter 間接設定數值
    struct number {
        var data1: Int = 50
        var data2: Int = 50
        var total: Int {
            get {
                return data1 + data2
            }
            set {
                data1 = newValue + total
            }
        }
    }
    
    var data = number()
    print(data.total)
        data.total = 200
    print(data.data1)
    
    • 輸出結果
      100
      300
      
  • 唯讀計算屬性
    struct number {
        var data1: Int = 50
        var data2: Int = 50
        var total: Int {
            return data1 + data2
        }
    }
    
    var data = number()
    print(data.total)
    
    • 輸出結果
      100
      

屬性觀察(property observer)

class number {
    var data: Int = 0 {
        willSet {
            print("新數值為 \(newValue)")
        }
        didSet {
            if data > oldValue {
                print("比起前一數值多了 \(data - oldValue)")
            }
            else {
                print("比起前一數值少了\(oldValue - data)")
            }
        }
    }
}
var DATA = number()
DATA.data = 100
DATA.data = 150
DATA.data = 100
  • 輸出結果
    新數值為 100
    比起前一數值多了 100
    新數值為 150
    比起前一數值多了 50
    新數值為 100
    比起前一數值少了50
    

型態屬性(instance property)

不需要建立物件,可以直接以結構名稱呼叫
struct number {
    static var data1: Int = 50
}
print(number.data1)
  • 輸出結果
    50
    

實例方法(instance method)

class data {
    var number = 0
    func add() {
        number += 10
    }
}
var DATA = data()
print(DATA.number)
    DATA.add()
print(DATA.number)
  • 輸出結果
    0
    10
    

修改值型態(mutating)

struct data {
    var number = 0.0
    mutating func add(newnumber: Double) {
        number += newnumber
    }
}
var DATA = data()
DATA.number = 50
print(DATA.number)
DATA.add(newnumber: 50)
print(DATA.number)
  • 輸出結果
    50.0
    100.0
    

型態方法(type method)

class data {
    class func text1() {
        print("方法一")
    }
    static func text2() {
        print("方法二")
    }
}
data.text1()
data.text2()
  • 輸出結果
    方法一
    方法二
    

results matching ""

    No results matching ""