【Swift】UserDefaultsのリセット方法


UserDefaultsのリセット周りのプロパティが結構変わっていて、ググる度にエラーが出て変換しまくっていたので、2021年4月現在のUserDefaultsのリセット方法をここに記します。

バージョン

Xcode: v.11.3
Swift: v.5.3.2

tl;dr

これでリセットできます。

let appDomain = Bundle.main.bundleIdentifier
UserDefaults.standard.removePersistentDomain(forName: appDomain!)

解説

「これでリセットできる!」では芸が無いので、一つ一つ意味を調べていきます。

let appDomain = Bundle.main.bundleIdentifier
UserDefaults.standard.removePersistentDomain(forName: appDomain!)

Bundle

Appleの公式ドキュメントによると、バンドルクラスは

A representation of the code and resources stored in a bundle directory on disk.

と書かれており、意訳すると

一つのディレクトリにまとめられたコードやリソースを代表するものと言えると思います。

つまり

プロジェクトファイル内のファイル・画像やBundle identifierなどの要素にアクセスするときに使うクラスらしいです。

main

また、このmain

現在実行中のファイルを返すらしく、今回はその中からbundleIdentifierを取得してるということみたいです。

その他にも、info.plistの中身やローカライゼーションの情報が取れるみたいです。

        let main: Bundle = Bundle.main
        print(main.bundleIdentifier) // プロジェクトのbundleIndentifier
        print(main.infoDictionary) // info.plistの中身
        print(main.preferredLocalizations) // ["en"]

removePersistentDomain(forName:)

UserDefaults.standardはおなじみとして、removePersistentDomain(forName:)はあまり馴染みがな人が多いと思います。

これも公式ドキュメントによると、

Removes the contents of the specified persistent domain from the user's defaults.

と定義されていて、意訳すると

指定されたuserDefaultsの永続的なドメインの中の要素を消すメソッドということらしいです。

なんでbundleIdentifierを渡すと消せるの?とおもって調べてみた所結構闇が深そうだったので、別の記事にまとめます。

終わりに

これでいちいちコピペしなくと済みそうです。Swift(Xcode)ってプロパティ名に変わったときに表示してれるのが良いですよね。すこ

参考文献