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?

【Swift】UserDefaults(Bool型)の初回起動時のnil対策がいらなかった話

Posted at

概要

  • UserDefaultsbool(forKey:)について

実装しようとしたこと

  • UserDefaultsを使った値でViewの表示制御をすることを考えた際にUserDefaultsnilであった場合にfalseが入っていないとクラッシュするのでは?と考えた

実装したコード

.onAppear {
    isEnabledShaking = UserDefaults.standard.bool(forKey: "isShakingEnabled") ?? false
}

remove ?? false

  • ?? false以降はどんな条件でも実行されないからremoveしろとアラートで怒られている。はて。

仕様の確認

  • bool(forKey:)を使用する際に値がnilである場合は、自動的にfalseを返してくれるという仕様が存在するとのこと。
  • ゆえにこの場合は明示的にnilだったらfalseにするなと書かなくてよいらしい。

解決

.onAppear {
    isEnabledShaking = UserDefaults.standard.bool(forKey: "isShakingEnabled")
}
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?