Swift: How to expand a tilde in a path String

前端 未结 4 1030
小蘑菇
小蘑菇 2021-02-20 04:22

How can I expand a path String with a tilde in Swift? I have a string like \"~/Desktop\" and I\'d like to use this path with the NSFileManager methods,

4条回答
  •  花落未央
    2021-02-20 04:48

    Tilde expansion

    Swift 1

    "~/Desktop".stringByExpandingTildeInPath
    

    Swift 2

    NSString(string: "~/Desktop").stringByExpandingTildeInPath
    

    Swift 3

    NSString(string: "~/Desktop").expandingTildeInPath
    

    Home Directory

    Additionally you can get the home directory like this (returns a String/String?):

    NSHomeDirectory()
    NSHomeDirectoryForUser("")
    

    In Swift 3 and OS X 10.12 it's also possible to use this (returns a URL/URL?):

    FileManager.default().homeDirectoryForCurrentUser
    FileManager.default().homeDirectory(forUser: "")
    

    Edit: In Swift 3.1 this got changed to FileManager.default.homeDirectoryForCurrentUser

提交回复
热议问题