0
1

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.

private(set)について

Posted at

・いつ使うか?

・取得をpublic、設定をprivateにしたい場合に利用される。

struct SomeStruct {
    
    private var setterName = "okadai"
    
    public var getterName: String {
        return setterName
    }
}

var some = SomeStruct()

//getterはpublicのため値の取得ができる
some.getterName // "okadai"

//setterはprivateのため値を変更しようとするとエラーになる
some.setterName = "New Name" //setterName' is inaccessible due to 'private' protection level


・しかし、この書き方だと少し面倒

Swiftでは、もっと簡潔に取得をpublicに、設定をprivateにする方法が用意されている。
それが、以下のようなアクセス修飾子である。

private(set)

実際に書き換えてみる

struct SomeStruct {
    
   private(set) var name = "okadai"
    
}

var some = SomeStruct()

//取得はpublicになっているため値の取得が可能
some.name

//設定はprivateになっているため値を変更しようとするとエラーになる
some.name = "New Name" //Cannot assign to property: 'name' setter is inaccessible

このように、private(set)という書き方をすることで、簡潔に取得と設定でアクセスレベルを指定することができる。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?