11
4

More than 3 years have passed since last update.

[Swift] private(set)を簡単に説明

Posted at

private(set)とは

private(set)が定義されているクラスや構造体の中では変更できるが、

それ以外の場所では読み取りのみ行う事が出来ます。

privateだけの場合は、定義されている場所内では変更・読み取りできるが、

それ以外では変更も読み取りも出来ません。

private(set)は変更できないようにアクセス制限するが読み取りは可能でprivateより制限がゆるいという事です。

使ってみた

private(set)の方はエラーにならず、読み取り出来ています。

class test {
    private var number1 = 0
    private(set) var number2 = 2
}

let Test = test()

class test2 {
    let a = Test.number1  //'number1' is inaccessible due to 'private' protection level
    let b = Test.number2
}
11
4
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
11
4