LoginSignup
2
3

More than 5 years have passed since last update.

[Swift] スクリプトが存在するディレクトリを絶対パスで取得する

Posted at

以下で取得可能。

path-to-me.swift
#!/usr/bin/env swift

import Foundation

guard let pathToMe = URL(string: "\(#file)", relativeTo: URL(fileURLWithPath: FileManager.default.currentDirectoryPath))?.path else {
  print("Error: current path of #file")
  exit(-1)
}
print( "path to me: \(pathToMe)" ) // path to me: /Users/uchcode/Desktop/path-to-me.swift

let __file__ = pathToMe as NSString
print( "NSString:")
print( "  full path: \(__file__)" ) // full path: /Users/uchcode/Desktop/path-to-me.swift
print( "  file name: \(__file__.lastPathComponent)" ) // file name: path-to-me.swift
print( "  directory: \(__file__.deletingLastPathComponent)" ) // directory: /Users/uchcode/Desktop
2
3
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
2
3