简体   繁体   中英

swift print string interpolation and folder path

in swift how do I specify a local file's path using string interpolation. When I do something like the following

let fileName = "myFile.jpg"
let fullPath = "folder/(fileName)"

I don't get a '/' at all between folder and the interpolated file name, and when I use '//' I get the '//' instead of the actual file name.

Any thoughts?

For simply printing folder/file path:

let fileName = "myFile.jpg"
let fullPath = "folder/\(fileName)"
print(fullPath)
/* Prints: folder/myFile.jpg */

let fileName = "myFile.jpg"
let fullPath = "folder\\\(fileName)"
print(fullPath)
/* Prints: folder\myFile.jpg */

Regarding string interpolation and escape characters in Swift, see Swift Language Guide - Strings and Characters :

String interpolation

String interpolation is a way to construct a new String value from a mix of constants, variables, literals, and expressions by including their values inside a string literal. Each item that you insert into the string literal is wrapped in a pair of parentheses, prefixed by a backslash:

 let multiplier = 3 let message = "\\(multiplier) times 2.5 is \\(Double(multiplier) * 2.5)" 

In the example above, the value of multiplier is inserted into a string literal as \\(multiplier) .

...

Special Characters in String Literals

String literals can include the following special characters:

  • The escaped special characters \\0 (null character), \\\\ (backslash), \\t (horizontal tab), \\n (line feed), \\r (carriage return), \\" (double quote) and \\' (single quote)

...

As vadian writes, however, methods to handle path components are preferable, see eg

I assume that you are trying to produce path for Windows, because forward slash / does not interfere with string interpolation in any way.

The proper expression for \\ inside interpolated string in front of an interpolation expression you need three backslashes:

let fullPath = "folder\\\(fileName)"
  • The first slash escapes the slash
  • The second slash is the slash that gets into the interpolated string
  • The third slash signals the beginning of an interpolation sequence \\(...)

more fun in a playground to show some API you might be interested in:

import Foundation

let url = NSURL(fileURLWithPath: "/foo/bar/")
let fileUrl = NSURL(string: "myfile.jpg", relativeToURL: url)
fileUrl?.absoluteString
fileUrl?.absoluteURL
fileUrl?.fileURL
fileUrl?.hasDirectoryPath
fileUrl?.pathComponents

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM