LoginSignup
1
2

More than 1 year has passed since last update.

[Swift] 一度だけ変更可能なプロパティを実装する方法

Last updated at Posted at 2022-06-29

初期値はnilで、その後1回値を代入したら、その後何度代入しても値が変わらないプロパティを実装したい。

didSetを使うと、以下のようにシンプルに実装できました。

struct User {
    var id: Int? {
        didSet {
            if oldValue != nil {
                id = oldValue
            }
        }
    }
}
var user = User()
print(user.id)  // 初期値はnil
user.id = 1
print(user.id)  // 1に変わった
user.id = 2
print(user.id)  // 1のまま変わらない
1
2
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
1
2