🍁

Swift: URL(fileURLWithPath:)についてメモ

2021/06/27に公開

SwiftのURLでどういうときディレクトリ扱いされるか。

実験
import Foundation

let urls = [
    // File 扱い
    URL(fileURLWithPath: "/Users/takuto/Desktop/sample"),
    
    URL(fileURLWithPath: "/Users/user/Desktop/sample.hoge"),
    
    URL(fileURLWithPath: "/Users/user/Desktop/sample",
                   isDirectory: false),
    URL(fileURLWithPath: "/Users/user/Desktop/sample.hoge",
                   isDirectory: false),
    URL(fileURLWithPath: "/Users/user/Desktop/sample/",
                   isDirectory: false),
    
    // Directory 扱い
    URL(fileURLWithPath: "/Users/takuto/Desktop/sample/"),
    
    URL(fileURLWithPath: "/Users/takuto/Desktop/sample.hoge/"),
    
    URL(fileURLWithPath: "/Users/user/Desktop/sample",
                   isDirectory: true),
    URL(fileURLWithPath: "/Users/user/Desktop/sample.hoge",
                   isDirectory: true),
    URL(fileURLWithPath: "/Users/user/Desktop/sample/",
                   isDirectory: true)
]

urls.forEach { url in
    print(url.hasDirectoryPath)
}
  • パスの最後に/がついていた場合、ディレクトリ扱い
  • isDirectoryを false にした場合、パスの内容に関わらずファイル扱い
  • isDirectoryを true にした場合、パスの内容に関わらずディレクトリ扱い

Discussion