LoginSignup
1
1

More than 1 year has passed since last update.

[Swift]ファイル・ディレクトリを削除する

Last updated at Posted at 2022-08-27

やりたいこと

ファイルやディレクトリを削除する。
(ディレクトリ削除の場合は、指定ディレクトリ配下を全て削除する。)

以下の2通りの指定方法での手順を記載する。

  • path指定 (ただのString)
  • URL指定 (URL型)

ファイルパス指定でのファイルの削除方法

FileManager.default.removeItem(atPath:) を使う。

    func deleteFileOrDirectory(path: String) {
        do {
            try FileManager.default.removeItem(atPath: path)
        } catch {
            print(error.localizedDescription)
        }
    }

URL指定でのファイルの削除方法

FileManager.default.removeItem(at:) を使う。

    func deleteFileOrDirectory(url: URL) {
        do {
            try FileManager.default.removeItem(at: url)
        } catch {
            print(error.localizedDescription)
        }
    }

まとめ

いずれの方法も例外が投げられるので、do-catch内で try をつけて実行する必要がある。

また、削除対象としてディレクトリ指定した際は、何の確認もなく指定ディレクトリ配下が全て消えるのでパス指定には注意してください。

##動作確認環境

Xcode: 13.4.1
iOS: 15.6.1
Swiftバージョン: 5.6.1

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