これはディレクトリ。
URL.documentsDirectory
では、これは何を指しているのか。
URL.documentsDirectory.appending(component: "xxx")
ファイルなのか、ディレクトリなのか、存在しないのか。
【Swift】URL appendingPathComponent() vs appending(component:)
👉 https://t.co/QuNo1FoAIa#プログラミング #ios— chanzmao (@maochanz) June 6, 2024
 
appendingPathComponent(_:) が Deprecated なので、
👉 appendingPathComponent(_:) | Apple Developer Documentation 
appending(component:directoryHint:) としています。
👉 appending(component:directoryHint:) | Apple Developer Documentation 
🤔 ディレクトリなのか
print(
  URL.documentsDirectory
    .appending(component: "xxx")
    .hasDirectoryPath
)
// false
👉 hasDirectoryPath | Apple Developer Documentation 
「ディレクトリではない」のですが、
そのURLにファイルがあるのか、
または、何も存在しないのか、
分かりません。
🤔 URL.resourceValues(forKeys:) を使う
👉 resourceValues(forKeys:) | Apple Developer Documentation 
この形でよく使われています。
extension URL {
  var isDirectory: Bool {
    (try? resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory == true
  }
}
print(
  URL.documentsDirectory
    .isDirectory,
  URL.documentsDirectory
    .appending(component: "xxx")
    .isDirectory
)
// true false
extension 内の条件式の左辺は、
URL先にリソースが存在してディレクトリのとき
→ true
URL先にリソースが存在してディレクトリでないとき
→ false
URL先にリソースが存在しないとき 
→ nil
となります。
URLの指すリソースが、ファイルとディレクトリのみであるとすれば、以下のように書くことができますね!
extension URL {
  private var resourceIsDirectory: Bool? {
    (try? resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory
  }
  var exists: Bool {
    resourceIsDirectory != nil
  }
  var isFile: Bool {
    resourceIsDirectory == false
  }
  var isDirectory: Bool {
    resourceIsDirectory == true
  }
}
let documents = URL.documentsDirectory
print(
  documents.exists,
  documents.isDirectory,
  documents.isFile
)
// true true false
let documentsXXX = URL.documentsDirectory
  .appending(component: "xxx")
print(
  documentsXXX.exists,
  documentsXXX.isDirectory,
  documentsXXX.isFile
)
// false false false
🤔 まとめ
URLResourceValues が扱う値はいろいろです。
👉 URLResourceValues | Apple Developer Documentation 
以下に、まとめておきます。
そもそもは、
「ファイルの存在の確認時に、制限のゆるい String に置き換えてからの FileManager.fileExists(atPath:) を使うのが面倒すぎる。」
ということがきっかけでした。
👉 fileExists(atPath:) | Apple Developer Documentation 
実体とURLは直感と違います。
 
		 
           
          