1

While I was trying to use Swift's String(format: format, args) method, I found out that I cannot print the formatted string directly without newline(\n) and brackets being added.

So for example, I have a code like this:

func someFunc(string: String...) {
    print(String(format: "test %@", string))
}

let string = "string1"
someFunc(string, "string2")

the result would be:

"test (\n    string1,\n    string2\n)\n"

However, I intend to deliver the result like this:

"test string1 string2"

How can I make the brackets and \n not being printed?

dumbfingers
  • 7,001
  • 5
  • 54
  • 80
  • 1
    See if [this Q&A](http://stackoverflow.com/questions/28957940/remove-all-line-breaks-at-the-beginning-of-a-string-in-swift) can help you out. – dfrib Jun 30 '16 at 14:43
  • 1
    You should rename `string` to `strings` to make it clearer that it's an array, not a string. – Alexander Jun 30 '16 at 14:49
  • What exactly are you trying to achieve? `"test %@"` has only *one* format specifier, how would you print two strings using that format? – Martin R Jun 30 '16 at 14:54
  • @MartinR I intend to print the elements inside the array – dumbfingers Jul 01 '16 at 14:06
  • `String(format: ...)` takes a format string and a variable list of arguments. For each argument there must be a format specifier. In your case, the format has only *one* format specifier, so only one argument is printed, no matter how many arguments you pass. – Therefore: Is your question "How to pass a variable argument list to String(format:...)?", or is your real question "How can I print a variable list of strings?" – Martin R Jul 01 '16 at 14:10

2 Answers2

2

Since string parameter is a sequence, you can use joinWithSeparator on it, like this:

func someFunc(string: String...) {
    print(string.joinWithSeparator(" "))
}

someFunc("quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog")
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

You will first need to concatenate your list of input strings, otherwise it will print as a list, hence the commas and parentheses. You can additionally strip out the newline characters and whitespace from the ends of the string using a character set.

var stringConcat : String = ''
for stringEntry in string {
    stringConcat += stringEntry.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
}

Then just print out the stringConcat.

SArnab
  • 575
  • 3
  • 7