LoginSignup
74
50

More than 5 years have passed since last update.

【Swift】セッター(Setter)、ゲッター(Getter)の処理を書く

Last updated at Posted at 2015-05-16

コンピューテッド・プロパティ(Computed Property)を使う。

コンピューテッド・プロパティ(Computed Property)は
ゲッターメソッドとセッターメソッドと呼ばれる2つのメソッドを提供するプロパティのこと。

使い方の例

Itemクラスにprice(税抜き価格)とintaxPrice(税込み価格)があります。

intaxPriceがComputedプロパティとなっており、
intaxPriceを取得する際にgetメソッドが呼ばれ、
値をセットする際に、setメソッドが呼ばれます。

class Item {

    // 税抜き価格
    var price:Double = 0

    // 税込み価格
    var intaxPrice:Double {

        // 値を取得するときに呼ばれる。
        get{
            return self.price*1.08
        }

        // 値がセットされるときに呼ばれる。
        set(p){
            price = p/1.08
        }
    }

}

下記がアクセスした際の具体的な例です。

item.intaxPrice = 108でintaxPriceのsetメソッドが呼ばれ、
itemに 108/1.08 (100)の値がセットされる。

item.intaxPriceでintaxPriceのgetメソッドが呼ばれ、
itemの値(150)*1.08の162が返ってくる。

// Itemクラスのインスタンスを作成
var item = Item()

// intaxPrice.setが呼ばれる
item.intaxPrice = 108
// itemに税抜き価格100がセットされている。
println(item.price)

item.price = 150
// intaxPrice.getが呼ばれる。(150*1.08の値=162が返ってくる。)
println(item.intaxPrice)

100
162
74
50
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
74
50