4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Swift】getter/setterについて

Posted at

はじめに

classやstruct内でたまに見かける、

get{
  return ~~
}
set{
  処理
}

このget/setって何??
と思ったので、勉強したことの備忘録を書きます!

getter/setter とは!

結論からざっくりいうと

getter : 他のプロパティから値を受け取り、処理した値を返す!
setter : 処理した値を他のプロパティに渡す!

て感じです!

実際にコードで見てみます!

get_set_playgriund

import UIKit

var str = "Hello, playground"

class Product {
    var name:String
    var price: Int
    
    var tax: Int {
        get{
            //priceからtax(消費税)を計算
            //他のプロパティ(price)の値を処理してtaxに返してますね!
            return Int(Float(price)*0.1)
        }
        set{
            //newValue(getから得たreturn値)からpriceを算出
            //taxの値(newValue)を処理して、他のプロパティ(price)に渡してますね!
            price = Int(Float(newValue)/0.1)
        }
    }
    init(name:String, price:Int) {
        self.name = name
        self.price = price
    }
}

var apple = Product(name: "青森県産リンゴ", price: 100)
print(apple.tax) //出力10

apple.tax = 90
print(apple.price)  //出力900
4
5
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
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?