2

When I print this:

print("dfi:.*\\{8766370\\}.*:6582.*")

the result on the log looks as expected:

>>>> dfi:.*\{8766370\}.*:6582.*

but when i construct the string dynamically the result looks wrong

let re = "dfi:.*" + "\\" + "{" + "\(section)" + "\\" + "}" + ".*:\(feed).*"
print(re)

>>>> dfi:.*\\{8766370\\}.*:6582.*"

Notice that there is a double slash in the second case "\" and I am not sure why. I tried using a single or triple slash but it prints wrong still.

EDIT - Adding code:

for (section,feeds) in toPurge {
  var regex = [String]()
  for feed in feeds {
    // dfi:\{(8767514|8769411|8768176)\}.*
    let re = "dfi:.*" + "\\" + "{" + "\(section)" + "\\" + "}" + ".*:\(feed).*"
    regex.append(re)
  }
  print(regex) // looks wrong ! bug in xcode?
  for r in regex {
    print(r) // looks perfect
  }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Avba
  • 14,822
  • 20
  • 92
  • 192

1 Answers1

0

You are literally printing everything inside of the array, which is going to show you the debugDescription variable, that is why you are seeing double slash. It is printing the literal value of the string, not the interpolated value you want.

If you want specific items in the array, you need to address the items inside of it by iterating through it, or addressing a certain index.

Here is your code showing it is the description:

import Foundation
let toPurge = [(8767514,[6582])]
for (section,feeds) in toPurge {
  var regex = [String]()
  for feed in feeds {
    // dfi:\{(8767514|8769411|8768176)\}.*
    let re = "dfi:.*" + "\\" + "{" + "\(section)" + "\\" + "}" + ".*:\(feed).*"
    regex.append(re)
    print(re)
  }
  print(regex[0]) // correct
  print(regex) // prints debugDescription
  print(regex.debugDescription) // prints debugDescription
  for r in regex {
    print(r) // looks perfect
  }
}
Knight0fDragon
  • 16,609
  • 2
  • 23
  • 44
  • Printing an array calls `debugDescription` on each element, and *that* is what displays escaped sequences for all special characters (like the double backslash). `description` would not do that. – Martin R Jul 05 '18 at 20:17
  • @MartinR I changed my answer to reflect as such since it makes more sense that it prints the `debugDescription`, but the description does also prints the literal string not the interpolated one (The code I provided before the edit shows that it is doing just that) – Knight0fDragon Jul 05 '18 at 20:48
  • The question (as I understand it) is about how a backslash in a string is printed, not about string interpolation. Try `let s = "a\\b" ; print(s.description) ; print(s.debugDescription)` – Martin R Jul 05 '18 at 20:52
  • @MartinR yes but you need to dig deeper, you see he is actually printing an array, not a string. He is confusing himself I guess. The question as I am seeing it is "Why is my variable not printing as I expect?" not "Why is String not printing as I expect?" – Knight0fDragon Jul 05 '18 at 20:58