FileKit是一个简单且可以使用表达式来管理文件的Swift框架。
示例代码:
路径
通过Path
结构体创建路径。
2 | let drive: Path = "/Volumes/Macintosh HD" |
3 | let file: Path = "~/Desktop/file\(1)" |
新建文件
可以通过在Path
上调用createFile()
来编写空白文件。
1 | try Path( ".gitignore" ).createFile() |
新建目录
可以通过在Path
上调用createDirectory()
来创建目录。
1 | try Path( "~/Files" ).createDirectory() |
2 | try Path( "~/Books" ).createDirectory(withIntermediateDirectories: false) |
创建符号链接
可以通过在Path
上调用createSymlinkToPath(_:)
创建符号链接。
1 | try Path( "path/to/MyApp.app" ).symlinkFile(to: "~/Applications" ) |
2 | print(Path( "~/Applications/MyApp.app" ).exists) |
查找路径
在桌面的5个层级目录内查找所有.txt后缀的文件。
1 | let textFiles = Path.userDesktop.find(searchDepth: 5 ) { path in |
2 | path.pathExtension == "txt" |
使用searchDepth
来指定查找的目录层级。
迭代路径
1 | for download in Path.userDownloads { |
2 | print( "Downloaded file: \(download)" ) |
当前工作目录
可以使用Path.Current
更改进程的当前工作目录。
要快速将当前工作目录更改为某个路径,请使用changeDirectory(_:)
方法:
1 | Path.userDesktop.changeDirectory { |
共同祖先目录
可以获得两个路径之间的共同祖先:
1 | print(Path.root.commonAncestor(.userHome)) |
2 | print( "~/Desktop" <^> "~/Downloads" ) |
3 | print(.UserLibrary <^> .UserApplicationSupport) |
+
操作
追加两个路径并返回结果
2 | let essay = Path.userDocuments + "My Essay.docx" |
也可以把字符串拼接成路径
1 | let numberedFile: Path = "path/to/dir" + String( 10 ) |
+=
操作
将右侧的路径添加到左侧路径。 也适用于String。
1 | var photos = Path.userPictures + "My Photos" |
2 | photos += "../My Other Photos" |
更多请参见开源代码主页。