LoginSignup
1
1

More than 1 year has passed since last update.

値型と参照型の使い分け

Posted at

値型とは

var a = 4.0 // aに4.0が入る
var b = a // bに4.0が入る(aがもつ4.0への参照ではなく、値である4.0が入る)
a.fromSquareRoot()
a // 2.0
b // bはaの変更の影響を受けずに4.0のまま

値型とは、インスタンスが値への参照ではなく値そのものを表す型。

参照型とは

class InBox {
    var value: Int

    init(value: Int) {
        self.value = value
    }
}

var a = InBox(value: 1) // aはInbox(value: 1)を参照する
var b = a // bはaと同じインスタンスを参照する

// a.value, b.valueは両方とも1
a.value // 1
b.value // 1

// a.valueを2に変更
a.value = 2

// a.value, b.valueは両方とも2
a.value // 2
b.value // 2

参照型とは、インスタンスが値への参照を表す型です。
参照型では一つのインスタンスが複数の変数や定数の間で共有されるので、ある値に対する変更はインスタンスを共有している他の変数や定数にも伝播します。

値型と参照型の使い分け

上記を踏まえたそれぞれの性質を考慮すると、安全にデータを取り扱うためには値型、状態管理などの変更の共有が必要となる範囲には参照型を使用すると良いでしょう。

1
1
1

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
1
1